简体   繁体   English

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

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

I am reading well structured, textual data in R and in the process of converting from character to numeric, numbers lose their decimal places.我正在阅读 R 中结构良好的文本数据,并且在从字符转换为数字的过程中,数字丢失了小数位。

I have tried using round(digits = 2) but it didn't work since I first had to apply as.numeric .我曾尝试使用round(digits = 2)但它没有工作,因为我第一次必须应用as.numeric At one point, I did set up options(digits = 2) before the conversion but it didn't work either.有一次,我确实在转换之前设置了options(digits = 2) ,但它也不起作用。

Ultimately, I desired to get a data.frame with its numbers being exactly the same as the ones seen as characters.最终,我希望得到一个data.frame ,其数字与被视为字符的数字完全相同。

I looked up for help here and did find answers like this , this , and this ;我在这里寻求帮助,确实找到了像这样这样这样的答案; however, none really helped me solve this issue.然而,没有人真正帮助我解决这个问题。

How will I prevent number rounding when converting from character to numeric?从字符转换为数字时,如何防止数字舍入?

Here's a reproducible piece of code I wrote.这是我编写的一段可重现的代码。

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.

It's how R visualize data in a tibble.这就是 R 如何在小标题中可视化数据。

The function map_dfc is not rounding your data, it's just a way R use to display data in a tibble .函数map_dfc不会四舍五入您的数据,它只是R用来在tibble显示数据的一种方式。

If you want to print the data with the usual format, use as.data.frame , like this:如果要以通常的格式打印数据,请使用as.data.frame ,如下所示:

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

Showing that your data has not been rounded.表明您的数据尚未四舍五入。

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM