【问题标题】:readr multiple columns' type at once一次读取多个列的类型
【发布时间】:2015-08-07 20:19:14
【问题描述】:

我尝试处理readr 函数。我的意思是,这是来自readr github 网页的示例:

read_csv("iris.csv", col_types = list(
  Sepal.Length = col_double(),
  Sepal.Width = col_double(),
  Petal.Length = col_double(),
  Petal.Width = col_double(),
  Species = col_factor(c("setosa", "versicolor", "virginica"))
))

有没有机会在read_csv 中使用一个可以同时确定多个列的col_double 的函数,例如grepl("Length|Witdh",col_names) = col_double()?

谢谢,

【问题讨论】:

  • 这可能没有帮助,但您不必指定每个列类型。您排除的任何内容都将以默认格式读取。因此,如果 Length 和 Width 列是数字,它们会自动加倍。
  • 是的,我知道。我只是以这段代码为例。我的 csv.file 中有 20 多列,其中大约 8 列我必须更改类。因此,我不想单独为每个列 col_...() 命令执行此操作。
  • @Nicolabo 你找到解决方案了吗?

标签: r types readr


【解决方案1】:

我已经提供了我在与此处类似的线程上发布的答案。如果有帮助,请告诉我。

将你想要的列名分配给一个向量;例如

custom_col_logic<- c("logi_one","logi_two") 

custom_col_date<- c("date_one","date_two") 

然后在每个函数上使用map() 函数将col_logic()col_date() 应用于单独的参数。然后将列名分配给每个参数。

#assign elments col_logic or col_date
type_logical <-map(custom_col_logic,~col_logic())

type_date <-map(custom_col_date,~col_date())

#now assign the column names to this
names(type_logtical)<-custom_col_logic

names(type_date) <-custom_col_date

这是诀窍,然后您需要使用 as.col_spec() 参数将这两个向量转换为 col_spec 类。

type_logical<- as.col_spec(type_logical)
type_date <- as.col_spec(type_date)

最后将一个新变量分配给cols(),然后将上述自定义列添加到该变量 #为类cols分配新变量

custom_col_type <- cols()

#assign the variables from before to this new variable's cols argument

custom_col_type$cols <- c(type_logical,type_date)

那么你就完成了!现在您可以将其用作read_csv() 中的col_type 参数中的直接参数

谢谢!

如果您觉得这有帮助,请投票或将其标记为最终答案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 2012-07-17
    • 2012-07-15
    • 1970-01-01
    相关资源
    最近更新 更多