Peter Flom
Peter Flom

Reputation: 2416

Writing to a filename that varies depending on a variable in R

Using R in Windows 7

I have a program that creates a big matrix called patients. It also has a variable called filenum. I would like to write the file to a table that varies based on filenum. For instance, if filenum = 1, I'd like it to write out to

"c:\personal\output1"

How can I do this?

I've been playing with paste and a little with gsub, but I can't get this to work

Thanks in advance

Peter

Upvotes: 0

Views: 1598

Answers (1)

Joshua Ulrich
Joshua Ulrich

Reputation: 176718

You could do this via lapply(split(), write.table, ...) or the equivalent function from plyr, but it would probably be fastest and cleanest to do this with a for loop. Something like:

for(fnum in unique(patients[,"filenum"])) {
  set <- which(patients[,"filenum"] == fnum)
  write.table(patients[set,], paste("c:/personal/output",fnum,sep=""))
}

Upvotes: 2

Related Questions