简体   繁体   English

将函数应用于数据框列表中的相应元素

[英]Apply function to corresponding elements in list of data frames

I have a list of data frames in R. All of the data frames in the list are of the same size.我在 R 中有一个数据框列表。列表中的所有数据框的大小都相同。 However, the elements may be of different types.然而,元素可以是不同的类型。 For example,例如,

在此处输入图片说明

I would like to apply a function to corresponding elements of data frame.我想将一个函数应用于数据框的相应元素。 For example, I want to use the paste function to produce a data frame such as例如,我想使用粘贴功能来生成一个数据框如

"1a" "2b" "3c"

"4d" "5e" "6f"

Is there a straightforward way to do this in R. I know it is possible to use the Reduce function to apply a function on corresponding elements of dataframes within lists.在 R 中是否有一种直接的方法可以做到这一点。我知道可以使用 Reduce 函数将函数应用于列表中数据帧的相应元素。 But using the Reduce function in this case does not seem to have the desired effect.但是在这种情况下使用 Reduce 函数似乎并没有达到预期的效果。

Reduce(paste,l)

Produces:产生:

"c(1, 4) c(\"a\", \"d\")" "c(2, 5) c(\"b\", \"e\")" "c(3, 6) c(\"c\", \"f\")"

Wondering if I can do this without writing messy for loops.想知道我是否可以在不编写凌乱的 for 循环的情况下做到这一点。 Any help is appreciated!任何帮助表示赞赏!

Instead of Reduce , use Map .而不是Reduce ,使用Map

 # not quite the same as your data
 l <- list(data.frame(matrix(1:6,ncol=3)),
           data.frame(matrix(letters[1:6],ncol=3), stringsAsFactors=FALSE))
 # this returns a list
 LL <- do.call(Map, c(list(f=paste0),l))
 #
 as.data.frame(LL)
 #  X1 X2 X3
 # 1 1a 3c 5e
 # 2 2b 4d 6f

To explain @mnel's excellent answer a bit more, consider the simple example of summing the corresponding elements of two vectors:为了进一步解释@mnel 的出色答案,请考虑对两个向量的相应元素求和的简单示例:

Map(sum,1:3,4:6)

[[1]]
[1] 5  # sum(1,4)

[[2]]
[1] 7  # sum(2,5)

[[3]]
[1] 9  # sum(3,6)

Map(sum,list(1:3,4:6))

[[1]]
[1] 6  # sum(1:3)

[[2]]
[1] 15 # sum(4:6)

Why the second one is the case might be made more obvious by adding a second list, like:通过添加第二个列表,可能会更明显地说明为什么第二个是这种情况,例如:

Map(sum,list(1:3,4:6),list(0,0))

[[1]]
[1] 6  # sum(1:3,0)

[[2]]
[1] 15 # sum(4:6,0)

Now, the next is more tricky.现在,下一个更棘手。 As the help page ?do.call states:正如帮助页面?do.call所述:

 ‘do.call’ constructs and executes a function call from a name or a
 function and a list of arguments to be passed to it.

So, doing:所以,这样做:

do.call(Map,c(sum,list(1:3,4:6)))

calls Map with the inputs of the list c(sum,list(1:3,4:6)) , which looks like:使用列表c(sum,list(1:3,4:6))的输入调用Map ,如下所示:

[[1]] # first argument to Map
function (..., na.rm = FALSE)  .Primitive("sum") # the 'sum' function

[[2]] # second argument to Map
[1] 1 2 3

[[3]] # third argument to Map
[1] 4 5 6

...and which is therefore equivalent to: ...因此相当于:

Map(sum, 1:3, 4:6)

Looks familiar!看起来很熟悉! It is equivalent to the first example at the top of this answer.它相当于这个答案顶部的第一个例子。

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

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