问题
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
来源:https://stackoverflow.com/questions/43901143/readrread-csv-pass-vector-of-character-column-names-to-import