繁体   English   中英

R:将列表中每个列表的元素求和,然后在数据框中返回结果

[英]R: sum the elements of each list on a list and return the result in a data frame

我在R中有一个清单清单; 每个列表都有一个Grep命令的结果,该命令指示找到搜索字符串的位置。 命令

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

产生

//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)

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

如果可能,请尝试解释我应该使用的语法; 我是R的新手,有时我发现如果同时嵌套多个内容,则很难理解示例。

其实只是我自己弄清楚了。 答案是:

data.frame(unlist(lapply(matches, function(x) sum(x))))

第一部分产生一个列表列表,每个列表都有一个元素,每个列表元素的总和

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

[[2]]
[1] 152

[[3]]
[1] 24

[[4]]
[1] 64

[[5]]
[1] 21

[[6]]
[1] 0

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

> unlist(lapply(matches, function(x) sum(x)))
[1]  24 152  24  64  21   0

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

暂无
暂无

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

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