Search code examples
rtidyversereadr

readr::read_csv use cols_only with spliced list


I am able to read in a subset of columns defined in cols_only like so:

x <- read_csv(filePath, col_types=cols_only(colA=col_character())
x <- read_csv(filePath, col_types=cols_only(colA='c'))

Both work fine, but I tried to create a list to pass into cols_only and splice it, like I do in many Tidyverse functions, but this one generates an error.

cols <- list(colA='c')
x <- read_csv(filePath, col_types=cols_only(!!!cols))

I tried this also as a named vector cols <- c(colA='c') but I get the error Error in !cols: invalid argument type.

Is this a limitation of the function? I saw this GitHub issue https://github.com/tidyverse/readr/issues/971 so was hoping this function could support this functionality.


Solution

  • If the splicing is not working, use do.call

    library(readr)
    df1 <- read_csv(file.choose(), col_types = do.call(cols_only, cols))
    

    Using a small reproducible example

    cols1 <- list(`Service Charge`='c', `MONTHLY FEES` = 'c')
    df1 <- read_csv(file.choose(), 
            col_types = do.call(cols_only, cols1))
    

    -output

    head(df1)
    # A tibble: 6 x 2
    #  `Service Charge`      `MONTHLY FEES`            
    #  <chr>                 <chr>                     
    #1 Customer Transfer Dr. INVESTMENT PURCHASE       
    #2 Customer Transfer Dr. INVESTMENT PURCHASE       
    #3 Miscellaneous Payment PAYPAL