user2238328
user2238328

Reputation: 259

R load script objects to workspace

This is a rookie question that I cannot seem to figure out. Say you've built an R script that manipulates a few data frames. You run the script, it prints out the result. All is well. How is it possible to load objects created within the script to be used in the workspace? For example, say the script creates data frame df1. How can we access that in the workspace? Thanks.

Here is the script...simple function just reads a csv file and computes diff between columns 2 and 3...basically I would like to access spdat in workspace

mspreaddata<-function(filename){

# read csv file
rdat<-read.csv(filename,header=T,sep=",")


# compute spread value column 2-3
spdat$sp<-rdat[,2]-rdat[,3]
}

Upvotes: 8

Views: 32504

Answers (2)

stanekam
stanekam

Reputation: 4030

So when you source that, the function mspreaddata is not available in your workspace? Because in there spdat is never created. You are just creating a function and not running it. That object spdat only exists within that function and not in any environment external to that. You should add something like

newObject <- mspreaddata("filename.csv")

Then you can access newObject

EDIT:

It is also the case that spdat is not created in your function so the call to spdat$sp<-rdat[,2]-rdat[,3] is itself incorrect. Simply use return(rdat[,2]-rdat[,3]) instead.

Upvotes: 1

stanekam
stanekam

Reputation: 4030

You should use the source function.

i.e. use source("script.R")

EDIT:

Check the documentation for further details. It'll run the script you call. The objects will then be in your workspace.

Alternatively you can save those objects using save and then load them using load.

Upvotes: 27

Related Questions