简体   繁体   English

当我尝试将因子列转换为数字时,我遇到了强制引入的 NA

[英]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.如果您注意到,您的数据上有一个美元符号和一个“B”字母(十亿)(这是一个字符),这就是您不能将其强制转换为数字数据的原因。 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我们可以使用parse_numberreadr ,它将仅从列中提取数字 substring 并转换 class

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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