rdoubleods

Specify col_types in readODS::read_ods


I want to read in R a range from an ods file, of which first column must be character, and the other 40 columns must be doubles. How do I specify the col_types? col_types = paste0("c", paste(rep("d", times = 40), collapse = "")) does not work, I get the error Unknown col_types. Can either be a class col_spec, NULL or NA. I cannot find any examples. Anyone a hint for a solution? Thanks!


Solution

  • col_types should be of class col_spec. It means, that you can define column type with readr::cols().

    Let's say you have this table in table.ods:

               A       B            C
    1 characters numbers againnumbers
    2          a       1            5
    3          a       2            6
    4          a       3            7
    5          a       4            8
    

    Then you can specify the columns with readr::cols(): the first column (named characters here) as characters by readr::col_character() and others by default as numbers with readr::col_double():

    library(readODS)
    library(readr)
    
    df <- read_ods("table.ods",
                   col_types = cols(
                       characters = col_character(),
                       .default = col_double())
    )
    
    str(df)
    #> 'data.frame':    4 obs. of  3 variables:
    #> $ characters  : chr  "0" "1" "2" "3"
    #> $ numbers     : num  1 2 3 4
    #> $ againnumbers: num  5 6 7 8
    

    (If you want to use simple method with e.g. "cdd", you need to convert that string to col_spec with readr::as.col_spec(), however it's not named and doesn't seem to work correctly with read_ods().)