[R] Parametrized object name in Save statement

Brian Diggs diggsb at ohsu.edu
Fri Apr 22 23:00:01 CEST 2011


On 4/22/2011 12:42 PM, John Dennison wrote:
> Greetings All,
>
> I am looking to write a parametrized Rscript that will accept a variable
> name(that also is the name of the flat file), transform the data into a data
> frame and preform various modeling on the structure and save the output and
> plot of the model. In this example i am using a rpart decision tree. The
> only problem i am having is integrating the parameter into the internal
> object name when tying to save it. Solving this one porblem will help me
> start blasting though 100's of models and saving their output for later use.
>
>
>
> I would call the script from command line as
> Rscript file_name.R argument
>
> for this example
>
> Rscript rpart_code.R Kyphosis
>
> #/bin/R
> args<- commandArgs(TRUE) # Read the argument
>
> require(rpart, quietly = TRUE)
>
> #for this example lets use the kyphosis data in the rpart package
> args<- "Kyphosis"
>
> X<-paste(args," ~.", sep ="") # create model formula call. X = "Kyphosis ~."
>
> assign(paste("cart_",args, sep =""),rpart(X,  method="class",
> data=kyphosis))
>
>
> #NOW MY TROUBLE. I have an rpart object but cannot save it under a file name
> that incorporates the parameter
> #Here is the file name
> file<-paste("cart_",args, sep ="")
>
> #hard coding the rpart object works
> save(cart_Kyphosis, file = file)
>
> However when I try to use the main parameter to accomplish this i get an
> error
>
> save(paste("cart_",args, sep =""), file = file)

How about

save(list=paste("cart_",args, sep =""), file = file)


> #I get
>
> Error in save(paste("cart_", args, sep = ""), file = file) :
>    object 'paste("cart_", args, sep = "")' not found
>
>
> #or
> save(get(paste("cart_",args, sep ="")), file = file)
>
> get(paste("cart_",args, sep ="")) # print the rpart object
>
> #I have tried several variation even creating a text line and parsing it
>
>
> paste("save(cart_", args, ", file=file)",sep="")
>
> [1] "save(cart_Kyphosis, file=file)"
>
> parse(text=paste("save(cart_", args, ", file=file)",sep=""))
>
> #or
>
> as.expression(parse(text =paste("save(cart_", args, ", file=file)",sep="")  ))
>
> expression(save(cart_Kyphosis, file=file))
> attr(,"srcfile")
> <text>
> attr(,"wholeSrcref")
> save(cart_Kyphosis, file=file)
>
> #nothing works. Any thoughts?
>
> #even this works but not the save
>
> png(filename=paste("cart_",args,".png" sep ="") , height = 500, width = 500,
> bg = "white")
> plot(get(paste("cart_",args, sep ="")))
> dev.off()
>
> #or
>
> print(get(paste("cart_",args, sep ="")))
>
>
> Many Thanks,
>
> John
>
> 	[[alternative HTML version deleted]]
>


-- 
Brian S. Diggs, PhD
Senior Research Associate, Department of Surgery
Oregon Health & Science University



More information about the R-help mailing list