1

I'm writing a function in R and I want to be able to call different objects from the function. I've got simple example of the problem I'm talking about (not the real code obviously).

example <- function(a,b){
  c <- a+b
  d <- a*b
  e <- a/b
  e
}

a <- 10
b <- 20

output <- example(a,b)
str(output)

output$c

My goal is for the last line to show the value of c defined in the function. In this code the only thing saved in output is the returned value, e.

I've tried changing the local and global environments, using <<- etc. That doesn't solve the problem though. Any help would be appreciated.

0

1 Answer 1

3

We can return multiple output in a list and then extract the list element

example <- function(a,b){
   c <- a+b
   d <- a*b
   e <- a/b
   list(c=c, d= d, e = e)
}

a <- 10
b <- 20

output <- example(a,b)[['c']]
output
#[1] 30

example(a,b)[['d']]
#[1] 200
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, worked perfectly. I'd be interested if you could provide more insight, if you can, about how functions set up the objects to be put out of a function.

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.