【问题标题】:R: sum the elements of each list on a list and return the result in a data frameR:对列表中每个列表的元素求和,并在数据框中返回结果
【发布时间】:2014-10-03 17:38:53
【问题描述】:

我在 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 列的简单数据框,每个“单元格”都包含 matches 的 6 个列表中的每个列表的总和。

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

【问题讨论】:

    标签: r list dataframe nested-lists


    【解决方案1】:

    其实只是我自己想出来的。答案是:

    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()函数将其转换为数据框。

    【讨论】:

    • 更简单:sapply(matches, sum)
    • 因为你只有 x 的论据,你可以这样做:data.frame(sapply(matches, sum))
    • O_O 谢谢你们!昨天我花了很多时间在这个上,现在我才看到它。不过,感谢您将我指向sapply,真的很有用。
    • @josilber,但sapply 可能比unlist(lapply(matches, sum)) 慢。比sapply 更好的是vapply(matches, sum, numeric(1L))
    • @josilber,然后试试rapply(matches, sum) :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    • 2021-01-14
    • 1970-01-01
    • 2015-01-31
    相关资源
    最近更新 更多