fifigoblin
fifigoblin

Reputation: 455

Lapplying a function over two lists of dataframes in 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.

Upvotes: 3

Views: 940

Answers (3)

Miff
Miff

Reputation: 7951

mapply would do what you need, for example:

myfunction <- sum
mapply(myfunction, list(1, 2, 3), list(10,20,30))
# [1] 11 22 33

Upvotes: 3

ThomasIsCoding
ThomasIsCoding

Reputation: 102710

Perhaps you can vectorize my_function via Vectorize, e.g.,

Vectorize(my_function)(list_A,list_B)

Upvotes: 1

akrun
akrun

Reputation: 887901

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]])

Upvotes: 2

Related Questions