gpt4 book ai didi

r - 如何强制 readr 考虑正确的小数/分组标记?

转载 作者:行者123 更新时间:2023-12-04 14:14:11 26 4
gpt4 key购买 nike

具有欧洲数字格式样式 (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 需要与您要读入的列的长度相同。

关于r - 如何强制 readr 考虑正确的小数/分组标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62064227/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com