Using a depth map for cbind columns in r
I am trying a cbind
list column in a list box with no success. If the list is 1 depth, an example would look like this, where I would like to add dates to my example data frames in each list object:
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, it cbind
decreases the list items instead of concatenating:
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
+3
source to share
1 answer
We need a recursive 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 for 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
+2
source to share