r - 读取多个文件,提取某列,删除某行,写入多个新文件
问题描述
我有数千个扩展名为 .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
intoafter_file1.txt
)。
我在做正确的事吗?如果您知道执行此操作的每个步骤,请提供帮助。
先感谢您
解决方案
您可以使用 :
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。
推荐阅读
- java - Java 运行时 exec 获取字符串数组的错误
- reactjs - React:编辑和替换用户输入(onChange)
- r - 如何密码保护从数据框中导出的 Excel?
- azure-data-factory - 映射数据流公共数据模型源连接器日期时间/时间戳列无效?
- javascript - 单击复选框时,如何在单个字段上使用 jquery 禁用客户端验证?
- c# - code_verifier 与 PKCE 授权请求中提供的 code_challenge 不匹配
- javascript - 每次点击如何在js中动态添加字体真棒图标
- eclipse - Eclipse:不包含 JNI_CreateJavaVM 符号”
- spring - 如何检查我的服务中的“elasticsearch is down”条件?
- eclipse - 无法在 WildFly 21 上使用 JSF 2.2 访问 CDI 支持 Bean