Converting mixed string into summed numeric

Hi there,

I have the below data. I want to convert these numbers to numeric and I want to do the same for the mixed cells too. In the case of "c(3,1)" I want those values summed together (answer should be 4) so I essentially want to remove all non numbers and sum them together (so in case of "1,2" it should become 3. Anyone know of an easy way to achieve this?

df <- data.frame(
  a = c("1","2","c(3,1)","1:3", "2:1"),
  b = c("2", "c(2,1", "1,2","4", "2")
)

Created on 2022-02-28 by the reprex package (v2.0.0)

Is this a typo or does your data include entries like this, too?

Hi there,

It does. I found a much better way to work with my data. In terms of solving it for the data provided here, this approach seems work decently well. One would still just have to wrap this and iterate over each cell but that is not so bad.

library(stringr)

x <- " c(3,1"

numbers <- gsub("[^0-9.-]", " ", x) %>% stringr::str_squish()
sapply(strsplit(numbers, ' '), function(x) sum(as.numeric(x)))
#> [1] 4


x <- "2:1"

numbers <- gsub("[^0-9.-]", " ", x) %>% stringr::str_squish()
sapply(strsplit(numbers, ' '), function(x) sum(as.numeric(x)))
#> [1] 3

x <- "2,1"

numbers <- gsub("[^0-9.-]", " ", x) %>% stringr::str_squish()
sapply(strsplit(numbers, ' '), function(x) sum(as.numeric(x)))
#> [1] 3


x <- "2"

numbers <- gsub("[^0-9.-]", " ", x) %>% stringr::str_squish()
sapply(strsplit(numbers, ' '), function(x) sum(as.numeric(x)))
#> [1] 2

Created on 2022-03-01 by the reprex package (v2.0.0)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.