Home > database >  How to merge columns from one file to another in R for many files?
How to merge columns from one file to another in R for many files?

Time:07-12

I have over 100 files e.g. File_1,,,,,,File_100 like the below:

Position    Likelihood  Alpha
11885.0000  8.457955e-02    2.089548e 02
21877.3906  2.160398e 01    1.509296e-05
31869.7812  1.268591e 01    2.130559e-05

And more 100 files e.g. File_1,,,,,File_100 like the below:

Position    Likelihood  Alpha   StartPos    EndPos
11885.0000  0.000000e 00    1.200000e 03    11885.0000  32345.0000
21877.3906  0.000000e 00    1.200961e-03    11885.0000  32345.0000
31869.7812  1.083378e-01    6.004804e-04    11885.0000  32345.0000

I am trying to combine the StartPos and EndPos from the other files to the above files where I will have five columns eventually. So, I did something like this:

a<-read.table("File_1", header = T)
b<-read.table("File_1", header = T)
c<-cbind(a,b[4:5])
write.table(c, file="File_1.txt")

My question is, how can I put this command in a loop where it goes over all the 100 files from Directory A and 100 files from Directory B and produces a new file? The two groups of 100 files are in different directories. Thank you for your help.

CodePudding user response:

Try this but you must specify the folders in your system e.g. "/Users/mohamed/File_"

for(i in 1:100){
    a<-read.table(paste0("/Users/Documents/First_results/new_file/V-3/Report_Chr_" , i), header = T)
    b<-read.table(paste0("/Users/Documents/First_results/new_file/V-4/Report_Chr_" , i), header = T)
    c<-cbind(a,b[4:5])
    write.table(c, file=paste0("Report_Chr_" , i , ".txt"))
    
}

this must save the new files in your working directory.

  • Related