passing named list to cols_only() [closed]

泄露秘密 提交于 2019-12-01 12:40:29

Sure, just use do.call to use the list as the parameters for the function, e.g.

library(readr)

read_csv(system.file('extdata', 'mtcars.csv', package = 'readr'),    # sample data from readr
         col_types = do.call(cols_only, list(cyl = 'i')))

#> # A tibble: 32 × 1
#>      cyl
#>    <int>
#> 1      6
#> 2      6
#> 3      4
#> 4      6
#> 5      8
#> 6      6
#> 7      8
#> 8      4
#> 9      4
#> 10     6
#> # ... with 22 more rows

The appropriate context of the cols_only argument is to spell out the columns you want to specifically read in as well as the type you would like to assign to the column.

Example:

data<-read_csv("blah.csv",
  n_max=100,
  col_types = cols_only(
              pumkins = col_factor(c("Hooligan", "Cinderella", "Big Max")),
              weight = col_double()
              ))

In this case I had it open the two columns named pumpkins and weight assigning each a type and in the case of pumpkins, factor levels. cols_only will accept a list, but the list as formatted above. You can place as many or as few column names and type descriptors in that list as you like.

If you want to just drop in a letter, then you can set it equal this way:

            c<-cols_only(
                  pumkins = col_factor(c("Hooligan", "Cinderella", "Big Max")),
                  weight = col_double())

Then drop c in straight up:

data <- read_csv("blah.csv",
           n_max = 100,
           col_types = c)
           )
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!