我试图学习不同的方法来使用列表中的对象作为FUN参数lapply.拿这个数据:
A <- list(a = matrix(0, ncol = 3, nrow = 3), b = matrix(0, ncol = 3, nrow = 3))
B <- list(a = matrix(1, ncol = 1, nrow = 3), b = matrix(1, ncol = 1, nrow = 3))
D <- mapply(FUN="list", A, B, SIMPLIFY=F, USE.NAMES=F)
D <- lapply(D, `names<-`, c("first", "second"))
D
[[1]]
[[1]]$`first`
[,1] [,2] [,3]
[1,] 0 0 0
[2,] 0 0 0
[3,] 0 0 0
[[1]]$second
[,1]
[1,] 1
[2,] 1
[3,] 1
[[2]]
[[2]]$`first`
[,1] [,2] [,3]
[1,] 0 0 0
[2,] 0 0 0
[3,] 0 0 0
[[2]]$second
[,1]
[1,] 1
[2,] 1
[3,] 1
Run Code Online (Sandbox Code Playgroud)
期望的结果:
[[1]]
[,1] [,2] [,3]
[1,] 0 0 0
[2,] 0 0 0
[3,] 0 0 0
[4,] 1 1 1
[[2]]
[,1] [,2] [,3]
[1,] 0 0 0
[2,] 0 0 0
[3,] 0 0 0
[4,] 1 1 1
Run Code Online (Sandbox Code Playgroud)
这就是我通常会这样做的方式:
lapply(D, function(x) rbind(x$first, as.numeric(x$second)))
Run Code Online (Sandbox Code Playgroud)
现在我想知道是否有办法避免使用function(x)和重复所有那些x s.就像是:
lapply(D, "rbind", <args>)
Run Code Online (Sandbox Code Playgroud)
我怎样才能让rbind(或任何其他函数)知道我指的是框架内的对象lapply?
谢谢,
K.
为了“避免使用function(x)和重复所有这些x”,我们可以使用with():
lapply(D, with, rbind(first, as.numeric(second)))
Run Code Online (Sandbox Code Playgroud)