特定的col_type = col_double(当数字为逗号和点时,没有结尾字符错误

时间:2019-03-25 09:07:58

标签: r readr

我在带有“ |”的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_types指定col_double。它不带col_types的情况下工作,但我真的需要指定col_types

1 个答案:

答案 0 :(得分:0)

您可以分两个步骤进行操作:将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创建