Reputation: 563
I would like to merge file dip.txt in all files one by one present in folder "1" based on column 1 of both files.
My code is the following:
setwd("~/Test/1")
require(tidyverse)
#read table (this folder 2 table need to place with every file present in folder 1 based on first column)
df1 <- read.table("~/Test/2/dip.txt", sep="\t", stringsAsFactors=FALSE, header=TRUE)
#I would like to run this script so that it read all file one by one present in folder 1 and save each output.
df2 <- read.table("5d98.txt", sep="\t", stringsAsFactors=FALSE, header=TRUE)
lst <- list(data.frame(df1), data.frame(df2))
df3 <- reduce(lst, full_join, by = "ID") %>% replace(., is.na(.), 0);
data.table::fwrite(df3, file="5d98output.txt", quote = F, sep = "\t", row.names = F)
Folder 1 file names are the random numbers. I would like to open file one by one present in folder 1, do my data manipulations, save that file with the original name with some suffix or prefix, close it and go on to the next file.
Upvotes: 1
Views: 1339
Reputation: 1298
To convert this to a for loop, first get a list of the .txt files in your working directory:
myfiles <- list.files(pattern="*.txt")
Then loop through each file, reading, joining with df1, and writing with minor modifications to your existing code:
for (file in myfiles) {
df2 <- read.table(file, sep="\t", stringsAsFactors=FALSE, header=TRUE)
lst <- list(data.frame(df1), data.frame(df2))
df3 <- reduce(lst, full_join, by = "ID") %>% replace(., is.na(.), 0);
data.table::fwrite(df3, file=paste0("output_", file), quote = F, sep = "\t", row.names = F)
}
Upvotes: 1
Reputation: 887118
We can use
files <- list.files()
lst1 <- lapplyfiles, function(x) read.table(x, stringsAsFactors = FALSE, header = TRUE))
lapply(lst1, function(x) full_join(df1, x, by = 'ID') %>% replace(., is.na(.), 0))
Upvotes: 1