首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否可以在cols_only()函数中使用tidyselect帮助程序?

是否可以在cols_only()函数中使用tidyselect帮助程序?
EN

Stack Overflow用户
提问于 2022-09-07 22:50:47
回答 1查看 33关注 0票数 0

我有这样一个.csv文件(除了真正的.csv文件有更多的列外):

代码语言:javascript
复制
library(tidyverse)

tibble(id1 = c("a", "b"),
       id2 = c("c", "d"),
       data1 = c(1, 2),
       data2 = c(3, 4),
       data1s = c(5, 6), 
       data2s = c(7, 8)) %>% 
  write_csv("df.csv")

我只想要id1,id2,data1和data2。

我可以这么做:

代码语言:javascript
复制
df <- read_csv("df.csv", 
               col_names = TRUE,
               cols_only(id1 = col_character(),
                         id2 =  col_character(),
                         data1 = col_integer(),
                         data2 = col_integer()))

但是,如前所述,我的真实数据集有更多的列,所以我希望使用tidyselect帮助程序只读取指定的列并确保指定的格式。

我试过这个:

代码语言:javascript
复制
df2 <- read_csv("df.csv",
         col_names = TRUE,
         cols_only(starts_with("id") = col_character(),
                   starts_with("data") & !ends_with("s") =  col_integer()))

但是错误消息表明语法有问题。是否有可能以这种方式使用tidyselect助手?

EN

回答 1

Stack Overflow用户

发布于 2022-09-08 08:08:19

我的建议在一定程度上是围绕着房子的,但它基本上允许你在“规则”而不是明确的基础上定制阅读规范。

代码语言:javascript
复制
library(tidyverse)

tibble(id1 = c("a", "b"),
       id2 = c("c", "d"),
       data1 = c(1, 2),
       data2 = c(3, 4),
       data1s = c(5, 6), 
       data2s = c(7, 8)) %>% 
  write_csv("df.csv")

# read only 1 row to make a spec from with minimal read; really just to get the colnames
df_spec <- spec(read_csv("df.csv", 
               col_names = TRUE,
        n_max = 1))

#alter the spec with base R functions startsWith / endsWith etc.
df_spec$cols <- imap(df_spec$cols,~{if(startsWith(.y,"id")){
  col_character()
} else if(startsWith(.y,"data") &
                                       !endsWith(.y,"s")){
  col_integer()
} else {
  col_skip()
}})

df <- read_csv("df.csv",
               col_types = df_spec$cols)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73642144

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档