readr::read_csv() — pass vector of character column names to import

我们两清 提交于 2019-12-23 17:23:21

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!