[英]using Map at depth to cbind columns in r
I am trying to cbind
a column to a list within a list, without success. 我试图将列
cbind
到列表中的列表,但没有成功。 If list was of depth 1, the example would look as follows, where I would like to add dates to my example data frames in each list object: 如果list的深度为1,则示例如下所示,我想在每个列表对象的示例数据框中添加日期:
ex_df_plain <- list(cbind(1,2),
cbind(3,4))
Map(cbind, as.list(c(2016, 2017)), ex_df_plain)
[[1]]
[,1] [,2] [,3]
[1,] 2016 1 2
[[2]]
[,1] [,2] [,3]
[1,] 2017 3 4
But as soon as I try to apply this to a list object where the depth of the list is greater than 1, the cbind
reduces the list elements instead of combining: 但是一旦我尝试将其应用于列表深度大于1的列表对象,
cbind
减少列表元素而不是组合:
at_depth_df <- list(as.list(c(1,2)), as.list(c(3,4)))
Map(cbind,
list(as.list(c(2015, 2016)), as.list(c(2017, 2018))),
at_depth_df)
[[1]]
[,1] [,2]
[1,] 2015 1
[2,] 2016 2
[[2]]
[,1] [,2]
[1,] 2017 3
[2,] 2018 4
My expected output should be 我的预期输出应该是
[[1]]
[[1]][[1]]
[,1] [,2]
[1,] 2015 1
[[1]][[2]]
[,1] [,2]
[1,] 2016 2
[[2]]
[[2]][[1]]
[,1] [,2]
[1,] 2017 3
[[2]][[2]]
[,1] [,2]
[1,] 2018 4
We need a recursive Map
我们需要一个递归
Map
Map(function(x, y) Map(cbind, x, y), lst1, at_depth_df)
where 哪里
lst1 <- list(as.list(c(2015, 2016)), as.list(c(2017, 2018)))
We can write a function to do this 我们可以写一个函数来做到这一点
f1 <- function(x, y, fun) {
if(is.atomic(x) && is.atomic(y)) {
x1 <- match.fun(fun)(x,y)
dimnames(x1) <- NULL
x1
} else {
Map(f1, x, y, MoreArgs = list(fun = fun))
}
}
f1(lst1, at_depth_df, cbind)
#[[1]]
#[[1]][[1]]
# [,1] [,2]
#[1,] 2015 1
#[[1]][[2]]
# [,1] [,2]
#[1,] 2016 2
#[[2]]
#[[2]][[1]]
# [,1] [,2]
#[1,] 2017 3
#[[2]][[2]]
# [,1] [,2]
#[1,] 2018 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.