Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply a function to all variables starting with specific pattern in R

Tags:

r

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 ?

like image 976
user1560292 Avatar asked Dec 20 '22 04:12

user1560292


1 Answers

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)))
like image 138
flodel Avatar answered May 03 '23 11:05

flodel