I want to use multiple objects created within a function with another function:

test1 <- function(x){
  y <- x + 1
  z <- x * 2
}

test2 <- function(...){
  test1(x)
  print(u <- y * z)
}

x <- 2

test2(test1)

It throws the error Error in print(u <- y * z) : object 'y' not found.

How can I reuse all objects assigned in a function without using the global assignment <<-?

2 Answers

1
RLave On Best Solutions

I'd use a simple return() with a list() or c():

test1 <- function(x){
  y <- x + 1
  z <- x * 2 # if you don't use return these two won't leave test1

  return(list(y=y, z=z)) # equivalent without return() is list(y=y, z=z)
#or: list(y=y, z=z)
}

test2 <- function(...){
  ret1 <- test1(x)
  print(ret1$y * ret1$z)
 #or: return(ret1$y * ret1$z)
}

Note that the use of return() is not necessary, since the last object not assigned in a function is returned automatically.

The use of return() may help with readability though.

A read about return().

0
Elie Ker Arno On

Your problem is about variable assignation: you are using a 'simple' assignment with the <- symbol. This mean the variable is assigned within its block, for instance y is defined within test1(). This mean you can not reuse it outside because it is not defined outside of test1(). To perfoerm this, try the <<- assignment symbol which assigns a variable in the upper environment and thus allow it to be reused outside of the block in which it is defined.