Convert written numbers with thousands separator to numeric value in R

Asked

Viewed 291 times

4

I have the following number that I am importing from a site, I put in the following way not to need to put all the import code of the data

a <- as.character("353.636.000.000")

I’d like to turn that into a number, but I’m not getting it

I tried to do it this way, separate the terms by . and then unite again and turn into number, but it didn’t work

temp2 <- strsplit(temp2, ".")

I need it to result in an object a with value of 353636000000

2 answers

6

With stringr you can do this:

library(tidyverse)

b <- a %>% 
  str_replace_all(pattern = '[.]', '') %>% 
  as.numeric()

class(b)
[1] "numeric"

5


It is also possible to solve the problem with R groundwork:

a <- as.character("353.636.000.000")
as.numeric(gsub("\\.", "", a))
## [1] 3.53636e+11

The function gsub is equivalent to a command of the type Locate and replace. Its syntax allows

  1. let’s look for a string (in this case, ., but we have to put the characters \\ to prevent the R take this as a regular expression)

  2. replace the string searched for with nothing (in this example, "" is the indicative of that)

  3. in a given object, which in the example is the character a

Browser other questions tagged

You are not signed in. Login or sign up in order to post.