读取多个文件,提取某列,删除某行,写入多个新文件。

问题描述 投票:1回答:1

我有数千个扩展名为.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文件,新文件的名称与原文件一致(例如,我需要将第1)和第2)点的结果导出到第2)点。before_file1.txtafter_file1.txt)为每个文件。

我这样做对吗?如果你知道每一个步骤,请帮忙。

先谢谢你

r loops csv subset
1个回答
0
投票

你可以使用.NET Framework 2.0来实现。

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中。

© www.soinside.com 2019 - 2024. All rights reserved.