有什么办法可以通过R中的read_excel(readxl)中的列名来分配col_types
我的应用程序正在使用readxl
包的read_excel
函数读取xls
和xlsx
文件。
在阅读xls
或xlsx
文件时,序列和列的确切数目是不知道的。 有15个预定义列 ,其中10列是必需的 ,其余5列是可选的 。 所以文件总是有最less10列, 最多15列。
我需要指定col-types
为强制性的10列。 我能想到的唯一方法是使用列名来指定col_types
因为我知道这个文件有全部10个列是强制性的,但它们是随机序列。
我试图寻找这样做的方式,但没有这样做。
任何人都可以帮我find一种方法来分配列名称的col_types?
我通过以下解决方法解决问题。 这不是解决这个问题的最好方法。 我已经读过两次excel文件 ,如果文件数据量非常大,将会影响性能。
首先阅读: 构build列数据types向量 – 读取文件以检索列信息(如列名,列数及其types),并构buildcolumn_data_types
vector
,该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" } }
第二次读取: 读取文件内容 –通过提供具有列data types
的vector
column_data_types
col_types
参数来读取excel文件。
#reading .xlsx file site_data <- read_excel(paste(File$datapath, ".xlsx", sep = ""), col_types = column_data_types)