【发布时间】:2019-06-02 12:03:28
【问题描述】:
我编写了一个循环,它输入几个文本文件,对每个文件执行一些功能并将它们组合起来。我在下面复制了它并注释了每一行。但是,i 中的第一个文件被读入(并添加到我的决赛桌)两次! 另外,期待简化这个循环。
source_files<-list.files(pattern="_output.txt") # This line finds all file ending with .txt
上面的 source_files 列出了要在下面的循环中输入的适当文件。
for (i in source_files){
if (!exists("final_table")){
df_import<-read.table(i, header=FALSE, sep="\t") # reads in each file
names<-unlist(strsplit(i,"_")) # reformats input file name and parses to 'names'
df_import$Sample<-names[1] # replaces col[1] header with first part of file name
df_import$DB<-names[2] # replaces col[1] header with first part of file name
final_table<-df_import # creates the final table data frame
rm(df_import) # remove excess df
}
if (exists("final_table")){
df_import<-read.table(i, header=FALSE, sep="\t") # reads in each file
names<-unlist(strsplit(i,"_")) # reformats input file name and parses to 'names'
df_import$Sample<-names[1] # replaces col[1] header with first part of file name
df_import$DB<-names[2] # replaces col[1] header with first part of file name
final_table <-rbind(final_table, df_import) # Adds to existing final table
rm(df_import)
}
}
这个循环运行良好,除了 final_table 有重复 - 有什么建议吗?
【问题讨论】:
-
您也可以在
for循环之外初始化final_table,完全不需要if/else。
标签: r for-loop nested-loops