如何强制 readr 考虑正确的 decimal/grouping 标记?

How to enforce readr to consider correct decimal/grouping mark?

具有欧洲数字格式样式 (1234.56 -> 1.234,56) 的 csv 文件应由 readr 函数或 fread() 处理。尽管 read_csv2() 应该正是为这个任务而设计的,但它基本上忽略了规范。它只会自动猜测数字格式。如果超过 3 位的第一个数字仅出现在文件末尾,即在达到 guess_max 之后(默认为 1000),这是有问题的。

如何以编程方式强制执行正确的格式设置?

library(readr)

data <- data.frame(var1 = c("", 4, 5, "124.392,45"),
                   var2 = c(1, 2, "4.783.194,43", 7))
write_csv2(data, "data.csv")

read_csv2("data.csv", guess_max = 2, 
          locale = locale(decimal_mark = ",", grouping_mark = "."))
# # A tibble: 4 x 2
#   var1  var2
#   <dbl> <dbl>
# 1    NA     1
# 2     4     2
# 3     5    NA
# 4    NA     7

read_csv2("data.csv", guess_max = 3, 
          locale = locale(decimal_mark = ",", grouping_mark = "."))
# # A tibble: 4 x 2
#   var1  var2
#   <dbl> <dbl>
# 1    NA     1
# 2     4     2
# 3     5    4783194.
# 4    NA     7

read_delim("data.csv", delim = ";", guess_max = 3, 
          locale = locale(decimal_mark = ",", grouping_mark = "."))
# # A tibble: 4 x 2
#   var1  var2
#   <dbl> <dbl>
# 1    NA     1
# 2     4     2
# 3     5    4783194.
# 4    NA     7

预先设置 col_types 似乎有帮助。在这种情况下是数字。

col_number() [n], numbers containing the grouping_mark

result <- read_csv2("data.csv", 
          # guess_max = 2, not needed if col_types are specified
          col_types = cols(var1 = col_number(),
                           var2 = col_number()),
          locale = locale(decimal_mark = ",", grouping_mark = "."))

result
# A tibble: 4 x 2
     var1     var2
    <dbl>    <dbl>
1     NA        1 
2      4        2 
3      5  4783194.
4 124392.       7 

正如 Adam 指出的那样,如果您设置 col_types,则无需猜测,因为 col_types 需要与您要读入的列的长度相同。