简体   繁体   English

在 R 中的两个数据帧列表上应用 function

[英]Lapplying a function over two lists of dataframes in R

I've got two lists of dataframes: list_A and list_B .我有两个数据框列表: list_Alist_B I want to take in consecutive dataframes from list_A and list_B and apply a custom function to them ( my_function ).我想从list_Alist_B中获取连续的数据帧,并对它们应用自定义 function ( 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).但是,我不知道如何处理lapply这样我就不必每次都输入数字(我有几百个元素)。 Also, I would like the results to be written to one list.另外,我希望将结果写入一个列表。

mapply would do what you need, for example: mapply会做你需要的,例如:

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 list s在这里,我们可以使用base R Map的 Map 将 function 应用于两个list的相应元素

out <- Map(my_function, list_A, list_B)

lapply can also be used, if we loop over the sequence of one of the list如果我们遍历list之一的序列,也可以使用lapply

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

which is similar to using a for loop这类似于使用for循环

out <- vector('list', length(list_A))
for(i in seq_along(list_A)) out[[i]] <- my_function(list_A[[i]], list_B[[i]])

Perhaps you can vectorize my_function via Vectorize , eg,也许您可以通过Vectorizemy_function进行矢量化,例如,

Vectorize(my_function)(list_A,list_B)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM