简体   繁体   English

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

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

I have a list of lists in R; 我在R中有一个清单清单; each list has the results of a Grep command indicating the position where the search string was found. 每个列表都有一个Grep命令的结果,该命令指示找到搜索字符串的位置。 The command 命令

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

produces 产生

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

I need to transform this to a simple data frame of 6 rows and 1 column, with each "cell" having the sum of each of the 6 lists of matches . 我需要将其转换为一个6行1列的简单数据框,每个“单元格”具有6个matches列表中每个项的总和。

If at all possible, please try to explain the syntax I should employ; 如果可能,请尝试解释我应该使用的语法; I'm new to R and sometimes I find examples difficult to follow if several things are nested at once. 我是R的新手,有时我发现如果同时嵌套多个内容,则很难理解示例。

Actually just figured it out on my own. 其实只是我自己弄清楚了。 The answer is: 答案是:

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

the first part yiels a list of lists with one element each, the summation of the elements of each list 第一部分产生一个列表列表,每个列表都有一个元素,每个列表元素的总和

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

[[2]]
[1] 152

[[3]]
[1] 24

[[4]]
[1] 64

[[5]]
[1] 21

[[6]]
[1] 0

the second part generates a vector from that. 第二部分从中生成向量。 Evidently it is a recursive function: 显然,这是一个递归函数:

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

Finally it is transformed into a dataframe using the data.frame() function. 最后,使用data.frame()函数将其转换为数据data.frame()

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

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