首页 > 解决方案 > 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有重复 - 有什么建议吗?

标签: rfor-loopnested-loops

解决方案


好吧,您测试该表是否存在于 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 中的单个数据帧中的函数有什么问题?


推荐阅读