Reputation: 317
I have a function to which I have to pass the dataset.
loading <- function(dataset){
merchants <- load(dataset)
return(merchants)
}
But when I use the loading function it returns a character vector
loading("capital.Rdata")
"capital"
How do I load the data inside the function?
Upvotes: 5
Views: 4784
Reputation: 121167
Use the envir
argument of load
to control the place where the loaded variables are stored.
Save some variables (to make this reproducible):
x <- 1:10
y <- runif(10)
z <- letters
save(x, y, z, file = "test.RData")
Define your loading function. This will return an environment containing x
, y
, and z
.
loading <- function(rdata_file)
{
e <- new.env()
load(rdata_file, envir = e)
e
}
Usage is as:
data_env <- loading("test.RData")
ls.str(data_env)
## x : int [1:10] 1 2 3 4 5 6 7 8 9 10
## y : num [1:10] 0.6843 0.6922 0.3194 0.0588 0.0146 ...
## z : chr [1:26] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" ...
Upvotes: 2
Reputation: 2142
The load()
command doesn't return the object stored in the RData file. Instead, it returns a character vector that lists the names of all the objects that were loaded from the Rdata file. Your object is apparently called capital
, so you could perhaps do something like this:
loading <- function(dataset){
merchants <- load(dataset)
return(get(merchants))
}
You pass the get()
function a string and it returns the object of that name.
Note that this won't work if there is more than one object saved in the RData file. Checking for the presence of more than one object, and potentially returning all objects, is left as an exercise for the reader.
Upvotes: 5
Reputation: 268
Check ls()
. You should have variables you saved in "capital.Rdata"
loaded. Your function returns the variable name you saved, which in this case should be capital
.
Upvotes: 0