如何在列表中的行总和中获取

时间:2016-08-11 07:09:03

标签: r

我有一个如下列表:

[[1]]
[1] "4 pieces of tissue"
[2] "4 pieces of tissue"
[3] "2 pieces of tissue" 

    [[2]]
[1] "2 pieces of tissue"
[2] "4 pieces of tissue"

[[3]]
[1] "6 pieces of tissue"
[2] "4 pieces of tissue"
[3] "3 pieces of tissue" 

[[4]]
[1] "2 pieces of tissue"

I want to sum the number of pieces of tissue in the list for each 'row' so that I get:

[[1]] 10
[[2]] 6
[[3]] 13
[[4]] 2

我该怎么做?

2 个答案:

答案 0 :(得分:1)

使用extract_numeric包中的tidyr的其他选项。

library(tidyr)
sapply(lst,function(t) sum(extract_numeric(t)))

答案 1 :(得分:0)

我们遍历list,使用str_extract提取所有数字部分unlist,转换为numeric并获取sum

library(stringr)
sapply(lst, function(x) sum(as.numeric(unlist(str_extract_all(x, "\\d+")))))
#[1] 10  6 13  2

base R选项(未使用包)

sapply(lst, function(x) sum(as.numeric(gsub("\\D+", "", x))))
#[1] 10  6 13  2

数据

lst <- list(
   c( "4 pieces of tissue",
     "4 pieces of tissue",
    "2 pieces of tissue" ),
 c( "2 pieces of tissue",
  "4 pieces of tissue"),
 c("6 pieces of tissue",
    "4 pieces of tissue",
    "3 pieces of tissue" ),
 "2 pieces of tissue")