将功能应用于数据帧列表中的相应元素 [英] Apply function to corresponding elements in list of data frames
问题描述
我在R中有一个数据帧列表.列表中的所有数据帧都具有相同的大小.但是,这些元素可以具有不同的类型.例如,
I have a list of data frames in R. All of the data frames in the list are of the same size. 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"
在R中是否有一种直接的方法.我知道可以使用Reduce函数将函数应用于列表中数据帧的相应元素.但是在这种情况下使用Reduce函数似乎并没有达到预期的效果.
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. But using the Reduce function in this case does not seem to have the desired effect.
Reduce(paste,l)
产生:
"c(1, 4) c(\"a\", \"d\")" "c(2, 5) c(\"b\", \"e\")" "c(3, 6) c(\"c\", \"f\")"
想知道我是否可以做到这一点而无需编写混乱的for循环.感谢您的帮助!
Wondering if I can do this without writing messy for loops. Any help is appreciated!
推荐答案
使用 Map
代替 Reduce
.
# 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
这篇关于将功能应用于数据帧列表中的相应元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!