Reputation: 81
Say I have a function
f <- function(){
# do things
return(list(zoo = x, vector = y, integer = z))
}
When I call this function using
result <- f()
Is there any way to call the return variables explicitly? Ie do I have to call it using
vara <- result$vara
varb <- result$varb
varc <- result$varc
Since if this function returns a lot of data types (whether it be data frames, zoo's, vectors, etc). The reason I dont want to bind into data frame is because not all variables are of the same length.
Upvotes: 4
Views: 4906
Reputation: 121167
with
or within
If the problem is just that you don't like typing result
, then you can use with
or within
to access elements inside the list.
with(result, vara + varb * varc)
This is a good, standard way of doing things.
list2env
You could copy the variables from the list using list2env
.
list2env(result, parent.frame())
This is slightly risky because you have two copies of your variables which may introduce bugs. If you are including the code in a package, R CMD check will give you warnings about global variables.
attach
This is a really bad idea (don't do this).
attach
is like a permanent version of with
. If you
attach(result)
then you can access each element without the result$
prefix. But it will lead to many horrendous, obscure bugs in your code when an error gets thrown before you detach it, and then you attach it a second time and drown in a variable-scope-swamp.
Upvotes: 4