r - R函数循环两次?
问题描述
我写了一个循环,它输入几个文本文件,对每个文件执行一些功能并将它们组合起来。我在下面复制了它并注释了每一行。但是,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有重复 - 有什么建议吗?
解决方案
好吧,您测试该表是否存在于 firstif
中,如果不存在,则创建它并在其中添加一行。因此,当您到达第二个时if
,该表确实存在,但它再次添加了该行。if
与其使用两个语句,不如使用一个if/else
. 也可能只是将final_table <-...
行移入if
并将其他行移出,这样您就没有太多重复的代码。
也许
for (i in source_files){
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
if (!exists("final_table")){
final_table<-df_import # creates the final table data frame
} else {
final_table <-rbind(final_table, df_import) # Adds to existing final table
}
rm(df_import) # remove excess df
}
那些有更好的方法来做到这一点,而不是每次循环和 rbinding。请参阅此答案:使用 rbind 将多个 .csv 文件加载到 R 中的单个数据帧中的函数有什么问题?
推荐阅读
- css - 如何在不重复具有不同值的语句的情况下简化我的 less 文件?
- android-studio - Android 应用首选项页面不显示工具栏
- google-colaboratory - 如何从 Google Colab 笔记本的单元格中删除表单?
- typescript - 角度 8 中模板驱动形式的最小长度误差
- python - 如何创建生成特定数量值的生成器函数?
- python - 有条件地合并时间变量上的数据帧
- mysql - 如何创建一个 sql 字符串以使用 group by 计算选定的行
- r - 如何在 Shiny 应用程序中计算并返回特定 R 函数的结果?
- apache-spark - 停止并重新启动在部署模式“集群”中执行的 SparkContext
- php - 如何从json中获取变量?(我不确定我的意思是关键字)