r - 如何在不丢失小数的情况下将数据框中的字符转换为数字
问题描述
假设以下格式的数据库
Voltage Global_intensity Sub_metering_1
<chr> <chr> <chr>
1 234.840 18.400 0.000
2 233.630 23.000 0.000
3 233.290 23.000 0.000
4 233.740 23.000 0.000
5 235.680 15.800 0.000
6 235.020 15.000 0.000
7 235.090 15.800 0.000
8 235.220 15.800 0.000
9 233.990 15.800 0.000
10 233.860 15.800 0.000
# ... with 2,075,249 more rows
我想将此列类型的字符变量转换为数字而不丢失十进制数字
df1$Voltage <-as.double(df1$Voltage,options(digits = 8))
Voltage Global_intensity Sub_metering_1
<dbl> <chr> <chr>
1 235. 18.400 0.000
2 234. 23.000 0.000
3 233. 23.000 0.000
4 234. 23.000 0.000
5 236. 15.800 0.000
6 235. 15.000 0.000
7 235. 15.800 0.000
8 235. 15.800 0.000
9 234. 15.800 0.000
10 234. 15.800 0.000
# ... with 2,075,249 more rows
现在我得到这样的结果,丢失了十进制数字。如何纠正它?
解决方案
关键是要区分显示的内容和存储的内容。 Voltage
仍然以全精度存储。
DF[] <- lapply(DF, as.numeric)
DF$Voltage
## [1] 234.84 233.63 233.29 233.74 235.68 235.02 235.09 235.22 233.99 233.86
笔记
Lines <- "Voltage Global_intensity Sub_metering_1
1 234.840 18.400 0.000
2 233.630 23.000 0.000
3 233.290 23.000 0.000
4 233.740 23.000 0.000
5 235.680 15.800 0.000
6 235.020 15.000 0.000
7 235.090 15.800 0.000
8 235.220 15.800 0.000
9 233.990 15.800 0.000
10 233.860 15.800 0.000"
library(tibble)
DF <- as_tibble(read.table(text = Lines, colClasses = "character"))
推荐阅读
- javascript - 如何在 React Select (V2) 中创建嵌套选项组?
- javascript - 使用 jQuery 从外部(本地)文件中获取文本
- c - 有一个符号链接的dirent,我怎样才能得到链接目标的路径名?
- bootstrap-4 - DNN 皮肤 - Bootstrap v4.1.1 - 显示空容器的设置
- angular - 未调用时加载延迟加载包的角度应用程序
- javascript - 可以拿到原版吗克隆纯javascript后
- java - 在处理 3 中创建可点击的网格
- c# - 在我的代码中找不到错误,它是一个使用列表存储操作和数字的计算器?
- sql - 为什么我的 SQL 代码会引发转换错误?
- solr - Solr HTTP Api - 响应状态