-1

I want to convert some numbers in a string into individual numbers and then sum it. I tried the following:

a <- as.character("100 + 100 + 50,00 + 100 + 50 + 5,000 + 
      100 + 100 + 100 + 100 + 100 + 100 + 
      20,000 + 3,000 + 20,000 + 100 + 1,300")


#remove comma
b <- gsub(",", "", a)

# replace + with comma
c <- gsub("+", "," , b, fixed = T)

#sum it
d <- as.numeric(c)

Warning message: NAs introduced by coercion

Agaz Wani
  • 5,514
  • 8
  • 42
  • 62
Amirul Islam
  • 407
  • 1
  • 6
  • 15

1 Answers1

0

After removing the comma, we can use eval with parse to directly evaluate the string.

a <- as.character("100 + 100 + 50,00 + 100 + 50 + 5,000 + 
      100 + 100 + 100 + 100 + 100 + 100 + 
                  20,000 + 3,000 + 20,000 + 100 + 1,300")

b <- gsub(",","",a)

eval(parse(text = b))
55350
www
  • 38,575
  • 12
  • 48
  • 84