4

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.

6
  • 1
    Can you be a little more precise so you don't want to use result$vara and result["vara"] then what type you want Commented May 19, 2015 at 5:42
  • Well, you can attach it if you really want to go that way. Commented May 19, 2015 at 5:52
  • 1
    Like in some languages you can just do [x,y,z] = f(). Its clean and doesnt take up many lines. When I have to define the variables as above, its always written as result$<blah> Commented May 19, 2015 at 5:52
  • 1
    Yeah, I like that syntax too, but I think it's not available in R. The ugly workaround is attach(setNames(f(),c("a","b"))) Commented May 19, 2015 at 5:54
  • If you only need one item, vara=f()$vara will work. Commented May 19, 2015 at 11:50

1 Answer 1

4

Use 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.

Use 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.

Use 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.