首页 > 解决方案 > 如何在不丢失小数的情况下将数据框中的字符转换为数字

问题描述

假设以下格式的数据库

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

现在我得到这样的结果,丢失了十进制数字。如何纠正它?

标签: rdataframedoublenumerictibble

解决方案


关键是要区分显示的内容和存储的内容。 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"))

推荐阅读