【问题标题】:Loop code through multiple .csv files in R通过 R 中的多个 .csv 文件循环代码
【发布时间】:2021-11-27 11:36:19
【问题描述】:

我正在尝试通过 50 多个 csv 文件运行一大段代码,但我不知道该怎么做。所有 csv 文件都有相同的列,但行数不同。

到目前为止,我有以下内容:

filelist<- list.files(pattern = ".csv") #made a file list with all the .csv files in the directory

samples <- lapply(filelist, function(x) read.table(x, header=T)[,c(1,2,3,5)]) #read all the csv files (only the columns I'm interested in)

output <- samples %>%
      rename (orf = protein) %>%   
      filter (!grepl("sp", orf)) %>% 
      write.csv (paste0("new_", filename))
#I want to rename a column and remove all rows containing "sp" in that column, then export the dataframe as new_originalfilename.csv 

任何帮助将不胜感激!

【问题讨论】:

    标签: r csv


    【解决方案1】:

    您可以在同一个 lapply 循环中执行此操作。

    library(dplyr)
    
    lapply(filelist, function(x) {
      read.table(x, header=T) %>%
        select(1, 2, 3, 5) %>%
        rename(orf = protein) %>%   
        filter(!grepl("sp", orf)) %>%
        write.csv(paste0("new_", x), row.names = FALSE)
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      • 2021-04-21
      • 1970-01-01
      • 1970-01-01
      • 2022-07-01
      相关资源
      最近更新 更多