gpt4 book ai didi

根据标题开始的位置将 CSV 读入 R

转载 作者:行者123 更新时间:2023-12-01 02:00:21 26 4
gpt4 key购买 nike

我有大量的 CSV 文件。有些标题从第一行开始,其他标题从第 3 行开始,其他的从第 7 行开始,依此类推。

标题看起来都一样,它们只是从不同文件的不同行开始。有没有办法有条件地 read.csv 文件从头开始的地方开始?

例如,如果我知道标题都具有第一列名称“office#”,我是否可以以某种方式指示 R 在第一次运行到字段“office#”时开始读取 csv 文件并将该行视为标题?

最佳答案

我有 4 个 CSV 文件 :

一张以 开头的表第 1 行 (虹膜.csv)

enter image description here

以及 3 个表头以 开头的表第 3、1 和 5 行 (销售_1、销售_2、销售_3)

enter image description here

只要我知道第一列名称 每个表,我可以使用 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 文件在哪里。

用法 :
smart_csv_reader('some_csvs/')

[1] "headers detected on rows:"
[1] 1 3 1 5

如您所见,函数 为每个表返回正确的行号 .它还 返回正确读取的每个表的列表 :

enter image description here

关于根据标题开始的位置将 CSV 读入 R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37126828/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com