Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lapplying a function over two lists of dataframes in R

Tags:

r

I've got two lists of dataframes: list_A and list_B. I want to take in consecutive dataframes from list_A and list_B and apply a custom function to them (my_function).

This works as desired:

my_function(list_A[[1]], list_B[[1]])
my_function(list_A[[2]], list_b[[2]])
...

However, I don't know how to do with lapply so that I don't have to type in the number each time (I have several hundred elements). Also, I would like the results to be written to one list.

like image 253
fifigoblin Avatar asked Nov 23 '25 21:11

fifigoblin


2 Answers

mapply would do what you need, for example:

myfunction <- sum
mapply(myfunction, list(1, 2, 3), list(10,20,30))
# [1] 11 22 33
like image 148
Miff Avatar answered Nov 26 '25 11:11

Miff


Here, we could use Map from base R to apply the function on the corresponding elements of both the lists

out <- Map(my_function, list_A, list_B)

lapply can also be used, if we loop over the sequence of one of the list

out <- lapply(seq_along(list_A), function(i) 
     my_function(list_A[[i]], list_B[[i]]))

which is similar to using a for loop

out <- vector('list', length(list_A))
for(i in seq_along(list_A)) out[[i]] <- my_function(list_A[[i]], list_B[[i]])
like image 23
akrun Avatar answered Nov 26 '25 12:11

akrun