简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM