Home > Software engineering >  How to pass the output of a function to another function in R?
How to pass the output of a function to another function in R?

Time:11-15

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.

CodePudding user response:

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.

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

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)
}

  • Related