在r中使用“深度映射”以cbind列
我正在尝试在r中使用“深度映射”以cbind列,r,R,我正在尝试cbind将列绑定到列表中的列表,但没有成功。如果列表的深度为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] [
cbind
将列绑定到列表中的列表,但没有成功。如果列表的深度为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
我的预期输出应该是
[[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
我们需要一个递归的
Map
Map(function(x, y) Map(cbind, x, y), lst1, at_depth_df)
在哪里
lst1谢谢你的功能,这是我见过的最漂亮的R代码
。。。它在处理html节点导出时非常有用
Map(function(x, y) Map(cbind, x, y), lst1, at_depth_df)
lst1 <- list(as.list(c(2015, 2016)), as.list(c(2017, 2018)))
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