rbindlist - 如何获得包含有关源信息的附加列?

rbindlist - how to get an additional column with info about a source?

我在一个文件夹中存储了 30 多个大型 .csv 文件。我想在 R 中将它们作为一个数据读取。frame/data/table 符合以下条件:

(1) 应跳过每个文件的前 25 行和后 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)

但是,我不知道如何获得包含每行来源信息的附加列...

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

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

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