I've got an R workspace with variables test1
, test2
, test3
, test4
,..testn
. These variables are all lists of the same length. I would like to combine these lists using mapply()
, as in the following example:
test_matrix=mapply(c, test1, test2,..testn)
How do I do this for all variables that start with "test"
, and do it in order test1
,test2
,..testn
?
To answer exactly what the OP asked for (mapply(c, test1, test2,..testn)
), do:
do.call(mapply, c(FUN = c, mget(paste0("test", 1:n))))
If you don't know how many (n
) lists you have and want to find them using a pattern:
do.call(mapply, c(FUN = c, mget(ls(pattern = "^test\\d+$"))))
Like the other answers so far, this method using ls
will not sort the objects properly if there are more than nine of them because they are sorted alphabetically. The longer but fully robust version would be:
test.lists <- ls(pattern = "^test\\d+$")
ordered.lists <- test.lists[order(as.integer(sub("test", "", test.lists)))]
do.call(mapply, c(FUN = c, mget(ordered.lists)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With