3

I am writing a function that accepts a vector of column names to be read from a CSV file using readr::read_csv().

I would like to read only the column names in the vector from the file, and I would like to use readr's default column-type guessing algorithm.

Is there a more direct way to accomplish this than creating a named list of col_guess() specifications as below?

# test csv data
test_csv <- "x,y,z\n1,2,3\n3,4,4\n5,6,7"

# vector of column names to import
col_names <- c("x", "y")

# create named list of column type specifications ("collectors" in readr-speak)
cols_to_get <- rep(list(col_guess()), 2)
names(cols_to_get) <- col_names

# use do.call() to provide my named list to readr's cols_only() function
readr::read_csv(test_csv, col_types = do.call(cols_only, cols_to_get))  

Prior art:
do.call() used with cols_only() identified at this SO question

treysp
  • 663
  • 6
  • 17
  • 1
    What is wrong with using `do.call()`? I have been trying to figure out how to do read in specific variables only if I have a list of their names (`vars <- c("a", "b", "c")`), and this works like a charm. It seems to work quick enough, too? Regardless, it could be a feature requested for `readr`, since it seems like a broad enough request. If you are not wedded to `readr`, `data.table::fread` has an argument called `select` that does this in a more direct way. – Mark White Sep 30 '17 at 19:43
  • For reference, [see this answer](https://stackoverflow.com/a/33201353/2204410) – Jaap Sep 30 '17 at 21:41
  • 1
    No problem, per se - it's just not intuitive, and I thought I might be overlooking a more direct way. Incidentally, I ended up using `fread` for reasons unrelated to column selection. – treysp Oct 02 '17 at 17:59

0 Answers0