rbindlist - 如何获取包含源信息的其他列?

问题描述 投票:0回答: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)

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

r fread rbindlist
1个回答
0
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.