Peter Flom
Peter Flom

Reputation: 2416

Reading a file in, then writing out a file with similar name in R

In R, I would like to read in data from a file, then do a bunch of stuff, then write out data to another file. I can do that. But I'd like to have the two files have similar names automatically.

e.g. if I create a file params1.R I can read it in with

source("c:\\personal\\consults\\ElwinWu\\params1.R")

then do a lot of stuff

then write out a resulting table with write.table and a filename similar to above, except with output1 instead of params1.

But I will be doing this with many different params files, and I can foresee making careless mistakes of not changing the output file to match the params file. Is there a way to automate this?

That is, set the number for output to match the number for params?

thanks

Peter

Upvotes: 2

Views: 976

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 270248

If the idea is just to make sure that all the outputs go in the same directory as the input then try this:

source(file <- "c:\\personal\\consults\\ElwinWu\\params1.R")

old.dir <- setwd(dirname(file))

write.table(...whatever..., file = "output1.dat")
write.table(...whatever..., file = "output2.dat")

setwd(old.dir)

If you don't need to preserve the initial directory you can omit the last line.

Upvotes: 1

Sacha Epskamp
Sacha Epskamp

Reputation: 47632

If your source file always contains "params" which you want to change to "output" then you can easilly do this with gsub:

source(file <- "c:\\personal\\consults\\ElwinWu\\params1.R")

### some stuff

write.table(youroutput, gsub("params","output",file) )
# Will write in "c:\\personal\\consults\\ElwinWu\\output1.R"

Edit:

Or to get .txt as filetype:

write.table(youroutput, gsub(".R",".txt",gsub("params","output",file)))
# Will output in c:\\personal\\consults\\ElwinWu\\output1.txt"

Edit2:

And a loop for 20 param files then would be:

n <- 20 # number of files

for (i in 1:n)
{
    source(file <- paste("c:\\personal\\consults\\ElwinWu\\params",i,".R",sep=""))

    ### some stuff

    write(youroutput, gsub(".R",".txt",gsub("params","output",file)))
}

Upvotes: 3

Related Questions