3

So I want to pass the output of func1 to func2.

func1 <- function(x, y, z) {
    k = x*2
    j = y*2
    i = z*2
}

func2 <- function(x, y, z) {
    func1(x, y, z)
    m = k * j * i
    return (m)
}

It keeps printing errors.

1
  • 1
    Your func1 is not returning anything. Your func2 does not need the return(), just the m. Commented Nov 14, 2021 at 20:44

4 Answers 4

6

Here is another solution. This is called a function factory which means a function that creates another function. Since func2 only uses the outputs of func1, it can find them through lexical scoping in its parent environment which is the execution environment of func1. Just note the additional pair of parentheses I used in order to call the function since the output of the first function is a function.

func1 <- function(x, y, z) {
  k <- x * 2
  j <- y * 2
  i <- z * 2
  func2 <- function() {
    m <- k * j * i
    m
  }
}

func1(1, 2, 3)()
[1] 48

For more information you can read this section of Hadley Wickham's Advanced R.

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

Comments

3

There are quite a few things going on here, and it really partly depends on if you are showing us a very simplified version. For example, are you really doing the same thing to x, y, z in the first function or are you possibly doing different things?

First, the i, j and k vectors that you are creating in func1() do not exist outside of func1(). As @akrun said you could rectify this bye making them into a vector (if they are always of the same type) or a list and then returning that.

So then you could get, say,

func1 <- function(x, y, z) {
    k <- x*2
    j <- y*2
    i <- z*2
    c(k, j, i)
}

At which point you could a a parameter to your second function.

func2 <- function(x, y, z) {
   ijk <- func1(x, y, z)
   prod(ijk)
  
}

Of course even easier if you can vectorize func1() (but I don't know how much you simplified).

func1v2 <- function(x, y, z) {
   
    2* c(k, j, i)
}

Comments

2

We may return a named list from the first function and then access the names of the output of the first function using with

func1 <- function(x, y, z) {
    list(k = x*2,
    j = y*2,
    i = z*2)
    
}
func2 <- function(x, y, z) {
     with(func1(x, y, z), k * j * i)
  
    
}

-testing


func2(3, 5, 6)

Comments

0

Since func2 only makes the product of a vector you do not need to define a second function. You can do it like this: First define func1 as you did

func1 <- function(x, y, z) {
    k = x*2
    j = y*2
    i = z*2
return(c(k,j,i))
}

Then use it inside the prod function like this

prod(func1(1, 2, 3))
48

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.