cs0815
cs0815

Reputation: 17408

transform character to number

This:

df <- data.frame(
    x = "50,000.00"
)

as.numeric(df$x)

Does not result in the number 50000. What could I do to obtain the number 50000 please?

Upvotes: 0

Views: 49

Answers (1)

akrun
akrun

Reputation: 887213

Remove the , part as it is a character and then it should work

as.numeric(sub(",", "", df$x))
#[1] 50000

If there are multiple instances of ,, use gsub (global substitution) instead of sub


Another option is parse_number which will work on character class. Here, the data.frame is created with default settings (stringsAsFactors = TRUE)

readr::parse_number(as.character(df$x))
#[1] 50000

Upvotes: 3

Related Questions