我有一个如下列表:
[[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
我该怎么做?
答案 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")