I need to read several different data inputs with read_csv(). I have somewhere saved the column types, which I want to use to check errors. My question is: how do I turn a string with columns types into a cols() object.
For example, this works:
cols('c', 'n')
But I need something like this:
aa <- c('c','n')
cols(aa)
This second call gives me an error:
> aa <- c('c','n')
> cols(aa)
Error in switch(x, _ = , - = col_skip(), ? = col_guess(), c = col_character(), : EXPR must be a length 1 vector
(updating my answer because sometimes you forget obvious things! )
The the col_types parameter (to any of the read_delim() variants) is more flexible than calling cols() directly, and is probably what you're going to actually use in practice. It takes either a list (ideally named) of string shorthand references, or a single string, so you'll need to as.list() your vector or str_flatten() / paste0() the strings together: