Amirul Islam
Amirul Islam

Reputation: 457

how to add or subtract comma separated numbers in r?

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,"

Upvotes: 1

Views: 276

Answers (2)

Artem Sokolov
Artem Sokolov

Reputation: 13691

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"

Upvotes: 1

jonathan.ihm
jonathan.ihm

Reputation: 108

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?

Upvotes: 0

Related Questions