具体 col_type = col_double 当数字有逗号和点时,没有尾随字符错误

specific col_type = col_double when number have comma and point, no trailing characters error

我在带有“|”的 txt 文件中对数据进行了平方具有这样值的分隔符数据

no| value
1|  3,123.00
2|  1,122.75

import it with this code:
library(readr)
data <- read_delim("file.txt", "|", trim_ws = TRUE, locale = locale(decimal_mark = "."), col_types = cols(no = col_double(),
value = col_double()))

Warning: 2 parsing failures.
row    col  expected               actual   file
  1 value   no trailing characters ,123.00 'file.txt'
  2 value   no trailing characters ,122.75 'file.txt'

这使得导入的数据为NA,我已经指定本地点小数点了。

为什么我的值是这样读的:,123.00?如果我用 col_double 指定 col_types,则缺少逗号前的第一个数字。它在没有 col_types 指定的情况下工作,但我真的需要指定 col_types

您可以分两步完成:将 value 读取为字符串,然后转换为数字。

library("tidyverse")
library("readr")

file <- "
no| value
1|  3,123.00
2|  1,122.75
"

x <- read_delim(
  file, "|", trim_ws = TRUE,
  col_types = cols(value = col_character())) %>%
  mutate_at(vars(value), parse_number)
x
#> # A tibble: 2 x 2
#>      no value
#>   <dbl> <dbl>
#> 1     1 3123 
#> 2     2 1123.

# Are fractions missing? No they are not.
x$value
#> [1] 3123.00 1122.75

reprex package (v0.2.1)

于 2019-03-26 创建