Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable in the file name for write.table in R

Tags:

r

Please help me with naive question (already googled, and tried a lot of variations, but failed): How save files with the variable in the file name for write.table in R? Script loop over the files in dir, apply some functions and then save results into the file with the same name but additional ending. Thank's!

for (x in list.files(pattern="SIM")) {
                      u <- read.table(x, header = T, row.names = 1, sep = " ")
                      ut <- t(u)
                      utm <- colMeans(ut)
                      utms <- sort(utm, decreasing = T)
                      write.table(utms, "$x.mean")
                      }
like image 217
chupvl Avatar asked Jul 21 '11 08:07

chupvl


People also ask

What is write table in R?

The R base function write. table() can be used to export a data frame or a matrix to a file. A simplified format is as follow: write.table(x, file, append = FALSE, sep = " ", dec = ".", row.names = TRUE, col.names = TRUE) x: a matrix or a data frame to be written.

How do I read a filename in R?

To list all files in a directory in R programming language we use list. files(). This function produces a list containing the names of files in the named directory.

How do I save a table in R?

To save data as an RData object, use the save function. To save data as a RDS object, use the saveRDS function. In each case, the first argument should be the name of the R object you wish to save. You should then include a file argument that has the file name or file path you want to save the data set to.


2 Answers

You can use paste to do this.

Try the following:

write.table(utms, file=paste(x, ".mean", sep=""))

paste concatenates character vectors. See ?paste for more details.

like image 124
Andrie Avatar answered Sep 28 '22 09:09

Andrie


The sprintf function can also be used for this type of thing with a little different syntax:

write.table(utms, file=sprintf("%s.mean",x))
like image 34
Greg Snow Avatar answered Sep 28 '22 09:09

Greg Snow