Home > database >  How can I change character class to numeric class?
How can I change character class to numeric class?

Time:01-13

I have a variable like this:

VALOR
3.554,34
56,34

But its class is "character" and when I code this:

gastosbolsonaro <- gastosbolsonaro %>% mutate(VALOR = as.numeric(VALOR))

Happening this:

Problem while computing `VALOR = as.numeric(as.character(VALOR))`.
i NAs introduced by coercion

And all value change to NA's.

I want to change value money to numeric class

CodePudding user response:

You can use parse_number from readr package

library(readr)
x <- c("3.554,34", "56,34")
parse_number(x, locale = locale(decimal_mark = ",", grouping_mark = "."))
[1] 3554.34   56.34

CodePudding user response:

Remove ., change , to . and then convert using as.numeric.

x <- c("3.554,34", "56,34")
. <- gsub(".", "", x, fixed = TRUE)
. <- sub(",", ".", .)
as.numeric(.)
#[1] 3554.34   56.34

Another base option using scan.

scan(text=gsub("\\.", "", x), dec=",")
#[1] 3554.34   56.34
  • Related