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.
mapply would do what you need, for example:
myfunction <- sum
mapply(myfunction, list(1, 2, 3), list(10,20,30))
# [1] 11 22 33
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]])
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