1) list We can return the desired variables in a list.
f2 = function(number) {
xx = NULL
savexx = NULL
savexx10 = NULL
for (i in 1:10) {
x = number*i
xx = c(xx,x)
}
list(save_phrase = "hello",
savexx = xx,
savexx10 = xx*10,
save = cbind(savexx,savexx10))
}
store = f2(1)
2) mget Another way to do this is to use mget
if the returned variables have a pattern to their names as in this case:
f3 = function(number) {
xx = NULL
savexx = NULL
savexx10 = NULL
for (i in 1:10) {
x = number*i
xx = c(xx,x)
}
save_phrase = "hello"
savexx = xx
savexx10 = xx*10
save = cbind(savexx,savexx10)
mget(ls(pattern = "save"))
}
store = f3(1)
3) gsubfn gsubfn has a facility for placing the list components into separate variables. After this is run save_phrase
, savexx
, savexx10
and save
will exists as separate variables.
library(gsubfn)
list[save_phrase, savexx, savexx10, save] <- f2(1)
4) attach Although this is not really recommended you can do this:
attach(f2(1), name = "f2")
This will create an entry on the search list with the variables that were returned so we can just refer to save_phrase
, savexx
, savexx10
and save
. We can see the entry using search()
and ls("f2")
and we can remove the entry using detach("f2")
.
5) assign Another possibility which is not really recommended but does work is to assign the components right into a specific environment. Now save_phrase
, savexx
, savexx10
and save
will all exist in the global environment.
list2env(f2(1), .GlobalEnv)
Similarly this will inject those variables into the current environment. This is the same as the prior line if the current environment is the global environment.
list2env(f2(1), environment())
6) Again, I am not so sure this is a good idea but we could modify f
to inject the outputs right into the parent frame. After this is run save_phrase
, savexx
, savexx10
and save
will all exist in the current environment.
f4 = function(number, env = parent.frame()) {
xx = NULL
savexx = NULL
savexx10 = NULL
for (i in 1:10) {
x = number*i
xx = c(xx,x)
}
env$save_phrase = "hello"
env$savexx = xx
env$savexx10 = xx*10
env$save = cbind(savexx,savexx10)
invisible(env)
}
f4(1)