Search code examples
rmultiple-columnsreadr

Converting all logical columns to doubles when reading csv files


How can I define ALL my columns to be assigned as col_double()? The command below gives me a list of known columns to assigned. I just want ALL of them to be:

library(readr)
df<- read_delim("df.csv", 
              delim = ";", escape_double = FALSE, 
              col_types = cols(x1 = col_double()), 
              trim_ws = TRUE)

I have been trying to read CSV files with millions of rows and over 100 columns. I already managed to define all of them as numeric when I WRITE the CSV but, even so, when I try to read it back, it still gives logical columns.

Furthermore, I cannot rely on simply increasing the number of rows used to guess, and I would very much like to avoid converting columns after I read them.

My problem is probably much more basic, but I tried read_csv(), read_delim(), fread()... and I just don't know how to select all columns to be read as doubles.


Solution

  • You can set the default column type with the .default argument

    library(tidyverse)
    data = iris %>% select(-Species)
    write_delim(data, "df.csv")
    df <- read_delim("df.csv", col_types = cols(.default = col_double()))
    sapply(df, class)