Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 将函数应用于数据帧列表中的相应元素_R_List - Fatal编程技术网

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

R 将函数应用于数据帧列表中的相应元素,r,list,R,List,我有一个R中的数据帧列表。列表中的所有数据帧大小相同。但是,这些元素可能是不同类型的。比如说, 我想对数据帧的相应元素应用一个函数。例如,我想使用粘贴函数生成一个数据帧,如 "1a" "2b" "3c" "4d" "5e" "6f" 在R中是否有一种简单的方法可以做到这一点。我知道可以使用Reduce函数在列表中的数据帧的相应元素上应用函数。但是在这种情况下使用Reduce函数似乎没有达到预期的效果 Reduce(paste,l) 产生: "c(1, 4) c(\"a\", \"d\")

我有一个R中的数据帧列表。列表中的所有数据帧大小相同。但是,这些元素可能是不同类型的。比如说,

我想对数据帧的相应元素应用一个函数。例如,我想使用粘贴函数生成一个数据帧,如

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

"4d" "5e" "6f"
在R中是否有一种简单的方法可以做到这一点。我知道可以使用Reduce函数在列表中的数据帧的相应元素上应用函数。但是在这种情况下使用Reduce函数似乎没有达到预期的效果

Reduce(paste,l)
产生:

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

我想知道我是否可以在不为循环写乱七八糟的东西的情况下做到这一点。感谢您的帮助

使用
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
#与您的数据不完全相同

L.P>为了更好地解释@ MNELL的优秀答案,请考虑总结两个向量对应元素的简单例子:

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)
第二种情况的原因可能会通过添加第二个列表变得更加明显,如:

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

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

[[2]]
[1] 15 # sum(4:6,0)
现在,下一个更棘手。正如帮助页面
?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.
这样做:

do.call(Map,c(sum,list(1:3,4:6)))
使用列表
c(总和,列表(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
…因此相当于:

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

看起来很眼熟!这相当于本答案顶部的第一个示例。

屏幕截图不能作为示例数据重现。哇,这真是太神奇了!So do.call将函数paste0和l中的每个项提供给Map,但是,Map在任何给定时间都只能访问l中的一个项,那么它如何能够将列表中不同项的内容粘贴在一起呢?如果不是这样的话,那么为什么映射(粘贴,l)不能简单地工作呢?你可以用
do.call(映射,c(粘贴0,l))
来简化一下,谢谢,这很有意义!非常优雅!