开发者

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

开发者 https://www.devze.com 2023-02-11 16:38 出处:网络
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.

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 o开发者_如何转开发f 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


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)))
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号