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:
If you just want to remove the first line and they are all txt documents you're probably better off using readLines (and writeLines) rather than read.delim and write.table.
Example below will remove the first line from the files in the list:
list_of_file_paths <- list(path1, path2, ...)
for (file in list_of_file_paths) {
writeLines(text = readLines(file)[-1], # take the contents minus the first line
con = file) # write back to the file
}
You can list all the files using list.files rather than listing each file name individually if that's what you mean:
list_of_file_paths <- list.files(path = "path/to/Document directory", full.names = T)
for (file in list_of_file_paths) {
writeLines(text = readLines(file)[-1], # take the contents minus the first line
con = file) # write back to the file
}