简体   繁体   中英

I'm getting NAs introduced by coercion when i try to convert a factor column to numeric

head(data$`Brand Value`)
#[1] $145.3 B $69.3 B  $65.6 B  $56 B    $49.8 B  $39.5 B 
#77 Levels: $10.4 B $10.5 B $10.6 B $11 B ... $9.6 B

data$`Brand Value`<-as.numeric(as.character(data$`Brand Value`))
#Warning message:  
#NAs introduced by coercion

If you notice, your data has a dollar sign and a "B" letter (Billion) on it (which is a character), that's the reason why you can't coerce it into a numeric data. You need to get rid of any characters or symbols if you want to change the data type into numeric. However, if you want to add a dollar sign in front of numeric data, you might want to refer to this link

We can use parse_number from readr which will extract only the numeric substring from the column and convert the class

library(readr)
data$`Brand Value` <- parse_number(data$`Brand Value`)

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