[R] write.table file="file.txt" help

Sundar Dorai-Raj sundar.dorai-raj at pdf.com
Tue Jan 27 00:04:16 CET 2004



Kristin Kay Nicodemus wrote:

> Hi all,
> 
> I have a R script that creates several input files for an analysis 
> program.  It loops through the matrix read into R and picks out 
> submatrices and then creates a separate output file for each 
> submatrix.  The loop works great, but I am having trouble getting all 
> the separate output files written.
> 
> The line I have is:
> 
> write.table(ch1d, file="C:/WINDOWS/Desktop/SNPs/haplo.txt", 
> row.names=F, col.names=F, append=F, quote=F)
> 
> Which works just fine if I just wanted to create a single file from the 
> loop.  However, I need to somehow get it to change the name of the 
> output file ("haplo.txt") each time it goes through the loop so it 
> doesn't overwrite each time.  In perl, I'd create $n=1 and increment up 
> each loop, and call the file something like "haplo.txt.$n"  
> 
> I tried to do something like that but R doesn't recognize the variable 
> that would be $n in perl (because it's part of the quoted name of the 
> output file).  Adding it after the ending " just gave me an error, as I 
> thought it would.
> 
> I also tried to use system(copy ...) to change the name of the file in 
> dos, but my knowledge of dos is abysmal, so I was unable to do it.
> 
> Any ideas on how to go about doing this would be most appreciated!
> 
> Thanks in advance,
> KK Nicodemus
> 

Use paste().

for(i in 1:n) {
   file <- paste("C:/WINDOWS/Desktop/SNPs/haplo", i, "txt", sep = ".")
   cat("Writing data to", file, "\n")
   write.table(ch1d, file=file,
             row.names=F, col.names=F, append=F, quote=F)
}

-sundar




More information about the R-help mailing list