使用readr :: read_csv()

时间:2019-12-13 16:19:19

标签: r readr

我有一个相当宽的数据集可以读取,顶部有1000多个缺失值,但是所有变量名都遵循相同的模式。有没有一种方法可以使用starts_with()来强制正确地解析某些变量?

MWE:

library(tidyverse)
library(readr)
mwe.csv <- data.frame(id        = c("a", "b"), #not where I actually get the data from
                      amount1   = c(NA, 20),
                      currency1 = c(NA, "USD")
)

mwe <- readr::read_csv("mwe.csv", guess_max = 1) #guess_max() for example purposes

我希望能够做到

mwe<- read_csv("mwe.csv", guess.max = 1 
         col_types = cols(starts_with("amount") = "d",
                          starts_with("currency") = "c"))
)

> mwe
# A tibble: 2 x 3
  id    amount currency
  <chr>  <dbl> <chr>   
1 a         NA NA      
2 b         20 USD   

但是我收到错误“ read_csv中出现意外'='”。有什么想法吗?我无法对其进行硬编码,因为列数会定期更改,但是模式(amountN)将保持不变。还将有其他列不是id或金额/货币。为了提高速度,我不希望增加guess.max()选项。

1 个答案:

答案 0 :(得分:0)

答案是作弊!

mwe             <- read_csv("mwe.csv", n_max = 0) # only need the col_names
cnames          <- attr(mwe, "spec") # grab the col_names
ctype           <- rep("?", ncol(mwe)) # create the col_parser abbr -- all guesses
currency        <- grepl("currency", names(cnames$col)) # which ones are currency? 
                # or use base::startsWith(names(cnames$col), "currency")
ctype[currency] <- "c" # do not guess on currency ones, use character
                       # repeat lines 4 & 5 as needed
mwe             <- read_csv("mwe.csv", col_types = paste(ctype, collapse = ""))