有没有办法让la laly声明也显示索引?更具体地说,请考虑以下示例:
mylist <- list(c(5,4),c(3,2), c(1,3))
myfunction<- function(values){
print("Adding values: ")
return(values[1] + values[2])
}
lapply(mylist, myfunction)
Run Code Online (Sandbox Code Playgroud)
有没有办法让我可以以某种方式打印"添加值:1""添加值:2"等.列表中每个元素的一个元素?
谢谢!
Ale*_*own 11
该功能mapply类似lapply但允许您提供多个向量或列表.
在您的情况下,您可以创建第二个向量,列表的长度相同,只是计数:
mapply(myfunction, mylist, seq_along(mylist))
Run Code Online (Sandbox Code Playgroud)
我们来试试吧:
myfunction<- function(values, index){
cat("Adding values (", index, "): ", values[1], "...", values[2], " = ", sum(values), "\n" )
invisible(values[1] + values[2])
}
mylist <- list(c(5, 4), c(3, 2), c(1, 3))
mapply(myfunction, mylist, seq_along(mylist))
Run Code Online (Sandbox Code Playgroud)
结果:
Adding values ( 1 ): 5 ... 4 = 9
Adding values ( 2 ): 3 ... 2 = 5
Adding values ( 3 ): 1 ... 3 = 4
Run Code Online (Sandbox Code Playgroud)
只是为了好玩,仔细阅读?lapply手册页会发现以下内容也有效:
myfunction<- function(values){
print(sprintf("Adding values: %i",substitute(values)[[3]]))
return(values[1] + values[2])
}
lapply(mylist, myfunction)
Run Code Online (Sandbox Code Playgroud)
这表明可以创建一个通用函数适配器来为原始函数(或任何其他函数)提供索引,修改为期望第二个索引参数:
myfunction<- function(values,index){
print(sprintf("Adding values: %i",index))
return(values[1] + values[2])
}
Run Code Online (Sandbox Code Playgroud)
现在适配器
lapply_index_adaptor=function(f)function(x,...)f(x,substitute(x)[[3]],...)
Run Code Online (Sandbox Code Playgroud)
现在是lapply调用,使用适配器:
lapply(mylist, lapply_index_adaptor(myfunction))
Run Code Online (Sandbox Code Playgroud)
message如果您的意思是消息,那么使用它会很好.
mylist <- list(c(5, 4), c(3, 2), c(1, 3))
Run Code Online (Sandbox Code Playgroud)
如果你想要索引(重读这可能是你想要的)
myfunction_idx <- function(idx, x) {
.x <- x[[idx]]
message(sprintf("Adding values %s:", idx))
sum(.x)
}
lapply(seq_along(mylist), myfunction_idx, x = mylist)
## Adding values 1:
## Adding values 2:
## Adding values 3:
## [[1]]
## [1] 9
##
## [[2]]
## [1] 5
##
## [[3]]
## [1] 4
##
Run Code Online (Sandbox Code Playgroud)
该plyr包将动态构建一个进度条(lapply将更快
library(plyr)
llply(mylist, sum, .progress = 'text')
Run Code Online (Sandbox Code Playgroud)