1

我在一个文件夹中存储了 30 多个大型 .csv 文件。我想在 R 中将它们作为一个 data.frame/data/table 读取,具有以下标准:

(1)每个文件的第一和最后25行应该跳过(每个文件的行数不同)

(2) 最后一列应包含有关行来源的唯一信息(例如原始文件中的 filename.csv.rownumber)。每个文件中的许多列也不同。

到目前为止,我有这个:

ASC_files <- list.files(pattern="*.csv")

read_ASC <- function(x){
ASC <-fread(x, skip=25)
return(ASC[1:(nrow(ASC)-25),])
}

ASC_list <-lapply(ASC_files, read_ASC)
ASC_all <- rbindlist(ASC_list, use.names=TRUE)

但是,我不知道如何获得一个额外的列,其中包含每行来源的信息......

4

1 回答 1

1

感谢大家评论我的问题。最后,我提出了这个解决方案:

ASC_files <- list.files(pattern="*.asc")
ASC_all <- sapply(ASC_files, function(x) read.csv(x, header=FALSE, col.names
paste0('V', 1:1268) , sep="", stringsAsFactors = FALSE))
#adding a new column with name of the source file
ASC_all <- mapply(cbind, ASC_all, "source"=ASC_files, SIMPLIFY = FALSE)
#adding a new column with row number
ASC_all <- map(ASC_all, ~rowid_to_column(.x, var="row"))
#removing last and first 25 rows in each dataframe of the list
ASC_all <- lapply(ASC_all, function(x) x[x$row<(nrow(x)-25),])
ASC_all <- lapply(ASC_all, function(x) x[x$row>25,])
#transforming the list into a dataframe with all data
ASC_all <- rbindlist(ASC_all)
#complementing the kolumn source with the row number (result: filename.csv.rownumber)
ASC_all$file <- paste0(ASC_all$file, '.', ASC_all$row)
#removing column with row numbers
ASC_all$row <- NULL

也许它不是最优雅和最有效的代码,但至少它可以工作。

于 2019-02-28T12:18:23.960 回答