r - 在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
解决方案
您有带有逗号(','
)的值,这些值在更改为数字时会变成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.))
推荐阅读
- mysql - 每次新数据进入数据库时如何运行python脚本
- javascript - 我如何在javascript中每个[“”]分割一个字符串
- python - 如何解决这个问题(Pytorch RuntimeError: 1D target tensor expected, multi-target not supported)
- javascript - 为变量赋值时,jQuery.parseHTML 是如何工作的?
- laravel - Laravel:auth()->尝试未定义的方法
- python - 我需要获取一个变量(用户电子邮件)并将其作为参数传递给嵌套类,但我无法使其工作
- asp.net - 即使我设置了静态机器密钥,oauth 持有者刷新令牌在应用程序池回收时也无效
- tinymce - TinyMCE - 向编辑器添加一个简单的按钮(不是工具栏)
- haskell - 大输入的阶乘函数返回负数
- sql - 根据商店选择每个产品的最新余额(SQL)