在 R 中使用 as.numeric() 时如何避免数字舍入?

How to avoid number rounding when using as.numeric() in R?

我正在阅读 R 中结构良好的文本数据,在从字符转换为数字的过程中,数字丢失了小数位。

我曾尝试使用 round(digits = 2),但自从我第一次必须申请 as.numeric 后就没用了。有一次,我确实在转换前设置了 options(digits = 2),但它也没有用。

最终,我希望得到一个data.frame,其数字与作为字符看到的数字完全相同。

我在这里寻求帮助,确实找到了像 this, this, and this 这样的答案;然而,none 确实帮我解决了这个问题。

How will I prevent number rounding when converting from character to numeric?

这是我写的一段可重现的代码。

library(purrr)
my_char = c("      246.00    222.22    197.98    135.10    101.50     86.45
            72.17     62.11     64.94     76.62    109.33    177.80")

# Break characters between spaces
my_char = strsplit(my_char, "\s+")

head(my_char, n = 2)
#> [[1]]
#>  [1] ""       "246.00" "222.22" "197.98" "135.10" "101.50" "86.45" 
#>  [8] "72.17"  "62.11"  "64.94"  "76.62"  "109.33" "177.80"

# Convert from characters to numeric.
my_char = map_dfc(my_char, as.numeric)


head(my_char, n = 2)
#> # A tibble: 2 x 1
#>      V1
#>   <dbl>
#> 1    NA
#> 2   246

# Delete first value because it's empty
my_char = my_char[-1,1]

head(my_char, n = 2)
#> # A tibble: 2 x 1
#>      V1
#>   <dbl>
#> 1  246 
#> 2  222.

这就是 R 在 tibble 中可视化数据的方式。

函数 map_dfc 不会舍入您的数据,它只是 R 用来在 tibble.

中显示数据的一种方式

如果你想用通常的格式打印数据,使用as.data.frame,像这样:

head(as.data.frame(my_char), n = 4)
       V1
#>1  246.00
#>2  222.22
#>3  197.98
#>4  135.10

显示您的数据没有四舍五入。

希望对您有所帮助。