R:对列表中每个列表的元素求和,并将结果返回到数据框中

s_a*_*s_a 2 r list nested-lists dataframe

我有一份R列表; 每个列表都有一个Grep命令的结果,指示找到搜索字符串的位置.命令

> matches<-lapply(ListOfFiles, function(x)
+ grep("SearchString",readLines(x),ignore.case = T))
Run Code Online (Sandbox Code Playgroud)

产生

//I copy the results that the function actually yields for the sake of the example

> matches<-list(c(11L, 13L), c(9L, 12L, 14L, 15L, 16L, 19L, 20L, 22L, 25L
+ ), c(5L, 8L, 11L), c(10L, 11L, 13L, 14L, 16L), c(5L, 7L, 9L), 
+ integer(0))

> matches
[[1]]
[1] 11 13

[[2]]
[1]  9 12 14 15 16 19 20 22 25

[[3]]
[1]  5  8 11

[[4]]
[1] 10 11 13 14 16

[[5]]
[1] 5 7 9

[[6]]
integer(0)
Run Code Online (Sandbox Code Playgroud)

我需要将其转换为6行1列的简单数据框,每个"单元格"具有6个列表中每个列表的总和matches.

如果可能的话,请尝试解释我应该使用的语法; 我是R的新手,有时候如果有几件东西嵌套在一起,我会发现难以理解的例子.

s_a*_*s_a 5

实际上只是我自己想出来的.答案是:

data.frame(unlist(lapply(matches, function(x) sum(x))))
Run Code Online (Sandbox Code Playgroud)

第一部分列出了列表,每个列表包含一个元素,即每个列表元素的总和

> lapply(matches, function(x) sum(x))
[[1]]
[1] 24

[[2]]
[1] 152

[[3]]
[1] 24

[[4]]
[1] 64

[[5]]
[1] 21

[[6]]
[1] 0
Run Code Online (Sandbox Code Playgroud)

第二部分从中生成一个向量.显然它是一个递归函数:

> unlist(lapply(matches, function(x) sum(x)))
[1]  24 152  24  64  21   0
Run Code Online (Sandbox Code Playgroud)

最后,使用该data.frame()函数将其转换为数据帧.

  • 更简单:`sapply(match,sum)` (2认同)