F. De Leo F. De Leo - 1 month ago 9
R Question

Naming output files in R

I'm working in

R
and I would like to export a txt file putting in its name the value of a particular variable; I read about the command
paste
and it works perfectly here:

write.table(mydata,file=paste(cn,"data.txt"))


where
cn
is the value to put at the beginning of the file
data.txt
. I would like to automatically put this file in an output folder where I keep all the other results. I try to do something like this:

write.table(mydata,file=paste(cn,"./output/data.txt"))


But it doesn't work. Any suggestion?

Answer

paste() just creates a string by concatenating the individual values and uses a space as default separator:

write.table(mydata, file = paste("./output/", cn ,"data.txt", sep = ""))

or with paste0(...), which is equivalent to paste(..., sep = ""):

write.table(mydata, file = paste0("./output/", cn ,"data.txt"))