Sebastian Zeki - 10 months ago 46

R Question

I have a list as follows:

`[[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

How can I do this?

Answer

We loop through the `list`

, use `str_extract`

to extract all numeric part, `unlist`

, convert to `numeric`

and get the `sum`

.

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

A `base R`

option (no packages used)

```
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")
```

Source (Stackoverflow)