【问题标题】:Is there any way to assign the col_types by column names in read_excel(readxl) in R有没有办法通过 R 中的 read_excel(readxl) 中的列名来分配 col_types
【发布时间】:2017-05-16 07:04:03
【问题描述】:

我的应用程序正在使用readxl 包的read_excel 函数读取xlsxlsx 文件。

之前读取xlsxlsx 文件时不知道列的顺序和确切数量。有 15 列预定义的列,其中 10 列 必填,其余 5 列 可选。因此,该文件将始终具有最少 10 列和 最多 15 列。

我需要将col-types 指定为强制性的 10 列。我能想到的唯一方法是使用列名来指定col_types,因为我知道该文件有所有 10 列都是强制性的,但它们是随机序列。

我试图寻找这样做的方法,但没有这样做。

谁能帮我找到一种按列名分配 col_types 的方法?

【问题讨论】:

  • 简短的回答是否定的;它不像reader::cols。如果结构非常规则,您可能可以伪造它,但这听起来不像您所拥有的。一个更简单的选择就是读取所有内容和子集。如果类型导致问题,请将所有内容都读取为字符并使用readr::type_convertlapply type.convert 进行清理。
  • 是的。我想到了你提到的那个选项。我只是想避免类型转换后文件读取的开销。但正如你所说,如果没有其他选择,我可能需要去。
  • 老实说,有 15 个变量,在您的数据达到数百万行之前,类型转换所花费的时间可以忽略不计。
  • @alistaire 同意。
  • @alistaire 因为我不知道确切的列数,所以我无法指定col_types。有什么想法吗?

标签: r excel readxl


【解决方案1】:

我通过以下解决方法解决了这个问题。虽然这不是解决这个问题的最佳方法。我已经两次读取 excel 文件,如果文件的数据量很大,这会影响性能。

初读: 构建列数据类型向量- 读取文件以检索列信息(如列名、列数及其类型)并构建@ 987654321@ vector 将为文件中的每一列提供datatype

#reading .xlsx file
site_data_columns <- read_excel(paste(File$datapath, ".xlsx", sep = ""))

site_data_column_names <- colnames(site_data_columns)

for(i in 1 : length(site_data_column_names)){  

    #where date is a column name
    if(site_data_column_names[i] == "date"){
         column_data_types[i] <- "date"

         #where result is a column name
         } else if (site_data_column_names[i] == "result") {
                      column_data_types[i] <- "numeric"

         } else{
                column_data_types[i] <- "text"
        }
}

第二次读取: 读取文件内容- 通过提供col_types 参数和vector column_data_types 来读取excel 文件,该参数具有data types 列.

#reading .xlsx file
site_data <- read_excel(paste(File$datapath, ".xlsx", sep = ""), col_types = column_data_types)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2020-08-03
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 2012-03-27
    相关资源
    最近更新 更多