首页 > 解决方案 > 读取多个文件,提取某列,删除某行,写入多个新文件

问题描述

我有数千个扩展名为 .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.txtinto after_file1.txt)。

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

先感谢您

标签: rloopscsvsubset

解决方案


您可以使用 :

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。


推荐阅读