首页 > 解决方案 > 在R中从因子转换为数字后丢失信息

问题描述

我有一个数据框,其中一些数字列是因子,我想转换为数值。但是我尝试了下面的代码,但它仍然丢失了信息。


> str(xdate1)
    'data.frame':   6 obs. of  1 variable:
     $ Amount.in.doc..curr.: Factor w/ 588332 levels "-0.5","-1","-1,000",..: 5132 57838 81064 98277 76292 71982
After converting to numeric i am losing the information. below is the output:
    > xdate1$Amount.in.doc..curr.<-as.numeric(as.character(xdate1$Amount.in.doc..curr.))
    Warning message:
    NAs introduced by coercion 
    > str(xdate1)
    'data.frame':   6 obs. of  1 variable:
     $ Amount.in.doc..curr.: num  -150 NA NA NA NA NA

标签: r

解决方案


您有带有逗号(',')的值,这些值在更改为数字时会变成NA,在转换为数字之前将其删除。

xdate1$Amount.in.doc..curr. <- as.numeric(gsub(',', '', xdate1$Amount.in.doc..curr.))

parse_number使用readr

xdate1$Amount.in.doc..curr. <- readr::parse_number(as.character(xdate1$Amount.in.doc..curr.))

推荐阅读