【问题标题】:Read multiple file, Extract certain column, Remove certain row, and write into multiple new files读取多个文件,提取某列,删除某行,写入多个新文件
【发布时间】:2024-01-13 14:53:02
【问题描述】:

我有数千个扩展名为 .txt 的文件,在一个公用文件夹中使用空格 ("") 作为分隔符。我需要:

  1. 提取某些列。我需要删除最后一列,例如只选择第 1、2、3 和 7 列。我已经用循环编写了这段代码:
    # Setting working directory
    workingdirectory <- "D:/FolderContainsThousandsFile"
    setwd(workingdirectory)

    # Listing the files in the folder with .txt extension
    FilesList <- list.files(workingdirectory, pattern = ".txt$")
    numberFiles <- length(FilesList)

    # Looping for all files
    for(f in 1:numberFiles){
    # read the file into tables
    FilterFile <- FilesList [f] %>% read.csv(sep = "", header = FALSE, stringsAsFactors = FALSE) %>% dplyr::select(-ncol(.)) # remove the last column
  1. 删除特定行。该文件包含几年的每日天气数据,然后我需要使用以下代码删除 2 月 29 日的所有数据:
    # Remove the 29th day in February
    columnNames <- c("year", "month", "day", "weather")
    FilterFile <- FilterFile %>% rename_at(c(1,2,3,7), ~columnNames) # renaming columns to indicate the column to be taken
    FilterFile <- FilterFile %>% filter(month != 2 | day != 29)
  1. 最后,我需要将点 1) 和 2) 的结果导出为所有文件中唯一的 .txt 文件,新文件的名称根据原始文件(例如:before_file1.txt 到 @987654324 @) 为每个文件。

我做对了吗?如果您知道执行此操作的每个步骤,请提供帮助。

提前谢谢你

【问题讨论】:

    标签: r loops csv subset


    【解决方案1】:

    你可以使用:

    library(dplyr)
    columnNames <- c("year", "month", "day", "weather")
    FilesList <- list.files(workingdirectory, pattern = "\\.txt$", full.names = TRUE)
    
    
    purrr::map(FilesList, ~{
         .x %>%
           #Read csv file
           read.csv(sep = "", header = FALSE, stringsAsFactors = FALSE) %>% 
           #Remove Last column
           select(-ncol(.)) %>%
           #Rename at particular position with columnNames
           rename_at(c(1,2,3,7), ~columnNames) %>%
           #Remove 29th Februaury
           filter(month != 2 & day != 29) %>%
           #Write the data back
           write.csv(paste0('after', basename(.x)), row.names = FALSE)
    })
    

    除非您有非常充分的理由将数据写入文本文件,否则我建议您改为将数据写入 csv。

    【讨论】:

    • 感谢您的努力。我已经尝试过这种方法。但它不起作用。我应该在 purrr::map(FilesList, ~{.x %>% and basename(x)) 上的“x”中输入什么命令来引用每个文件名?
    • @SidiqPambudi 你能再试一次吗,basename 中的最后一行应该是.x。我已经更正了答案。
    • 结果是:basename(.x) 中的错误:找不到对象 '.x' 我错过了放置某些命令吗?
    • 现在我在filterrename_at 之后错过了一个管道。抱歉,再次更新答案。
    • 对不起。还是有错误,Error in eval(lhs, parent, parent) : object 'renamecol' not found