【问题标题】:I'm getting NAs introduced by coercion when i try to convert a factor column to numeric当我尝试将因子列转换为数字时,我遇到了强制引入的 NA
【发布时间】:2020-06-27 17:25:08
【问题描述】:
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

【问题讨论】:

  • 这些值都不能强制转换为数字。它们都有非数字字符,例如 $B
  • 试试data$``Brand Value``&lt;-as.numeric(gsub("[^\\.[:digit:]]", "", x))

标签: r data-manipulation


【解决方案1】:

如果您注意到,您的数据上有一个美元符号和一个“B”字母(十亿)(这是一个字符),这就是您不能将其强制转换为数值数据。如果要将数据类型更改为数字,则需要去掉任何字符或符号。但是,如果您想在数字数据前添加美元符号,您可能需要参考 this link

【讨论】:

    【解决方案2】:

    我们可以使用readr中的parse_number,它只会从列中提取数字子字符串并转换类

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-26
      相关资源
      最近更新 更多