Here is one possibility (though a little complicated and verbose). If you have a list of the columns that you want to change, then we can create a single string for the col_types
. From the help for ?read_csv
, the col_types
argument can take a single string of column shortcuts (e.g., iiDl
). Here, I read in the column names, then bind that to the list of columns that need to be changed. Then, I replace any NA
with the default type, i
, then I collapse all column types into a single string. Then, I use that to define the col_types
in read_csv
.
library(tidyverse)
col_classes <-
bind_rows(
read_csv(my_file, col_types = cols(.default = "c"))[0, ],
tibble(
logi_one = 'i',
logi_two = 'i',
date_one = 'D',
date_two = 'l'
)
) %>%
mutate(across(everything(), ~ replace_na(., "i"))) %>%
as.character(.[1, ]) %>%
paste0(., collapse = "")
results <- read_csv(my_file, col_types = col_classes)
However, this obviously would not work for read_csv2
. But you could collapse every row back down, like this:
output <-
data.frame(apply(read_csv(myfile), 1, function(x)
paste(x, collapse = ",")))
names(output) <- paste(names(results), collapse = ",")