I have 4 个 CSV 文件:
一张表的标题开始于row 1(虹膜.csv)
以及 3 个表头的开头为第 3、1 和 5 行(销售_1、销售_2、销售_3)
只要我知道第一列名称对于每个表,我可以使用smart_csv_reader函数来确定每个标头的开始位置,以及读取每个 CSV 文件的正确行号:
first_columns <- c('sepal.length', 'month', 'month', 'month')
smart_csv_reader <- function(directory) {
header_begins <- NULL
file_names <- list.files(directory, pattern=".csv$")
for(i in 1:length(file_names)) {
path <- paste(directory, file_names[i], sep='', col='')
lines_read <- readLines(path, warn=F)
header_begins[i] <- grep(first_columns[i], lines_read)
}
print('headers detected on rows:')
print(header_begins)
l <- list()
for(i in 1:length(header_begins)) {
path <- paste(directory, file_names[i], sep='', col='')
l[i] <- list(read.csv(path, skip=header_begins[i]-1))
}
return(l)
}
只需传入目录所有 CSV 所在的位置。
Usage:
smart_csv_reader('some_csvs/')
[1] "headers detected on rows:"
[1] 1 3 1 5
正如你所看到的功能返回每个表的正确行号。它也是返回正确读取的每个表的列表: