This relates to my other question, and may help me get to a solution. The following structure is a 3x1 matrix with each element containing a list.
cb <- structure(list(c("apples", "and", "pears"), c("one", "banana"
), c("pears", "oranges", "and", "pizza")), .Dim = c(3L, 1L),
.Dimnames = list(NULL, "s"))
I'd like to recursively assign 4 as the length of each matrix element, and then concatenate them all, so that the result is
# [1] "apples" "and" "pears" NA "one" "banana"
# [6] NA NA "pears" "oranges" "and" "pizza"
Here's the manual way to do it.
`length<-`(cb[[1]],4)
# [1] "apples" "and" "pears" NA
`length<-`(cb[[2]],4)
# [1] "one" "banana" NA NA
`length<-`(cb[[3]],4)
# [1] "pears" "oranges" "and" "pizza"
I'd like to do this without looping, either by using recursion or writing a bquote
expression. I think I need to use do.call
, but I can't figure out the right way to do it. My code is right now is
do.call(`length<-`, list(c(cb, recursive=TRUE), 12))
# [1] "apples" "and" "pears" "one" "banana" "pears"
# [6] "oranges" "and" "pizza" NA NA NA
but this appends the NA
values to the end of the concatenated vector, and I want to recursively append them because I probably will not know how many rows (list elements) cb
contains. There are recursive =
arguments in both unlist
and c
, maybe those need to be used here.
An answer that replaces x
with the current list level, like in the following, would work.
replicate(3, quote(`length<-`(cb[[x]], 4L)))
#[[1]]
#`length<-`(cb[[x]], 4L) # x = 1
#
#[[2]]
#`length<-`(cb[[x]], 4L) # x = 2
#
#[[3]]
#`length<-`(cb[[x]], 4L) # x = 3