I'd like to write a function to read a csv, which takes 2 arguments, a file name and a column name. Then use the column name as a argument to cols()
This is a cut down version of what I'm trying to do:
Read_a_file <- function(my_file, my_col){
read_csv(file.path('../data',my_file),
col_names = c('xdate', my_col), # File with 2 columns, "xdate" and one other
col_types = cols(
xdate = col_date(format = '%d/%m/%Y'),
my_col = col_double())). # This doesn't work because I need the string specified by my_col not "my_col"
I'd like to be able to specify a col_type for the my_col column. At present I can't do this because in cols() I need the string contained within the object my_col, not the string "my_col".
I'm trying to bring in only one column from a CSV.
How do I pass the value of an object to a function within another function.
I was answering the first.
For the second, the my_col variable isn't called, so it's in the global environment, perhaps. However, the problem lies in the right object in the right way.
readr provides a as.col_spec() function to convert a list to a column specification. You can also specify what you want the default column specification to be with the .default name, in this case we want to skip columns that are not specified. Combining these two things you can create the function you were attempting.