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")
}
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.
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.
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.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With