简体   繁体   中英

Running a loop for editing multiple txt files in Rstudio

I want to open multiple .txt files within RStudio and have created a loop to open these using the for function. I want to just delete the first line in each document and then save the .txt file again under the same name. I have been able to open one .txt file at a time using this script:

setwd("Document directory")
Test_data<-read.delim("File Name.txt")
colnames(Test_data)<-NULL
Test_data<-Test_data[-c(1),]
write.table(Test_data, file = "File Name 1.txt", sep = "\t",row.names = FALSE, col.names = FALSE)

AND I have been able to create the loop with this script:

    library(tidyverse)
library(fs)
setwd("Document directory")
file_paths <-fs::dir_ls("Document directory")
file_paths

file_contents<- list()
#This creates a loop
for(i in seq_along(file_paths)){
  file_contents[[i]]<-read.delim(
    file = file_paths[[i]]
  )
}
View(file_contents)

But I am unsure how to put this together to create a loop to edit each document in the folder I am working in.

Would anyone be willing to help, please?

Suppose you want to edit every csv -file inside your "Document directory", remove the first row and the column names.

library(tidyverse)
library(fs)
setwd("Document Directory")

files <- fs::dir_ls(type = "file", regex = "[.]csv$")

#This creates a loop
for(i in seq_along(files)) {
  tmp_content <- read.delim(files[i])[-c(1),]
  write.table(tmp_content, file = paste0("new_", files[i]), sep = "\t",row.names = FALSE, col.names = FALSE)
}
  • The arguments of dir_ls filter for files, especially .csv -files. You can change this behaviour, for example regex = "[.]txt$" filters for every .txt -file. If you don't what to filter any files by their ending, just remove the regex = ... part from function dir_ls() .
  • Next we loop over those file, read them and remove the first row.
  • Finally we write them back into the files. I used file = paste0("new_", files[i]) to prefix the new files with "new_". Since col.names = FALSE is one of the arguments, you don't need colnames(tmp_content) <- NULL .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM