【发布时间】:2024-01-13 14:53:02
【问题描述】:
我有数千个扩展名为 .txt 的文件,在一个公用文件夹中使用空格 ("") 作为分隔符。我需要:
- 提取某些列。我需要删除最后一列,例如只选择第 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
- 删除特定行。该文件包含几年的每日天气数据,然后我需要使用以下代码删除 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) 和 2) 的结果导出为所有文件中唯一的 .txt 文件,新文件的名称根据原始文件(例如:
before_file1.txt到 @987654324 @) 为每个文件。
我做对了吗?如果您知道执行此操作的每个步骤,请提供帮助。
提前谢谢你
【问题讨论】: