1

How to perform a calculation on numbers that are comma separated. For example

result <- 10,000 + 5,000 + 60,000

gives the error

Error: unexpected ',' in "result <- 10,"

Prradep
  • 5,506
  • 5
  • 43
  • 84
Amirul Islam
  • 407
  • 1
  • 6
  • 15
  • 1
    Are your numeric columns structured this way (i.e. with commas)? or are you asking how to perform calculations with dollar representation of numbers in R? – acylam Aug 28 '17 at 16:49
  • You have to remove commas or else R does not view it as a numeric column. You can use gsub(',', '',df$column_name) to get rid of commas. – Katie Aug 28 '17 at 16:51

2 Answers2

1

While using gsub and format functionality will certainly do the trick, another alternative is to use some of tidyverse packages. The code is arguably easier to read and interpret than gsub:

library( readr )
library( scales )
comma( parse_number("10,000") + parse_number("5,000") + parse_number("60,000") )
# [1] "75,000"
Artem Sokolov
  • 13,196
  • 4
  • 43
  • 74
0

Remove commas, do your math, and then add them back. Documentation:

In R: remove commas from a field AND have the modified field remain part of the dataframe

Comma separator for numbers in R?

jonathan.ihm
  • 108
  • 1
  • 1
  • 8