rnorouzian
rnorouzian

Reputation: 7517

Connecting two functions in R

Question:

Suppose I have a function called Hy (see R code below). If I want to have the 3 objects in the Hy function become input for the By function what should I do?

Note: These functions should not become a closure function (i.e., combining Hy and By into a single function), instead the Hy and By functions must remain "separate."

Details:

Hy <- function(n){

  A <- rnorm(n)
  B <- rcauchy(n)

invisible( list(A = A, B = B, n = n) ) ## Making all elements & arguments recognizeable 
                                        # outside the function "Hy".

}

Hy(2)

Now the By function needs "A", "B", and "n" from the Hy function to work:

By <- function(A, B, n){

  C = A + 1 
  D = B + 1
  E = n + 1

 return( list (C = C, D = D, E = E) )
 }

By(A = A, B = B, n = n)  ## HERE I need A, B, n from "Hy" function above to be recognized and used 
                          # as input for "By" function

Upvotes: 1

Views: 118

Answers (2)

Sathish
Sathish

Reputation: 12723

If you want to update A and B as well in the global environment use <<- as assignment operator inside Hy function.

Hy <- function(n){

  A <- rnorm(n)
  B <- rcauchy(n)

  invisible( list(A = A, B = B, n = n) ) ## Making all elements & arguments recognizeable 
  # outside the function "Hy".
}

By <- function(A, B, n){

  C = A + 1 
  D = B + 1
  E = n + 1

  return( list( C , D, E ) )
}

Hy_vals <- Hy(1)
By(A = Hy_vals$A, B = Hy_vals$B, n = Hy_vals$n)
# C        D        E 
# 2.718926 1.586720 2.000000 

Upvotes: 1

Gregor Thomas
Gregor Thomas

Reputation: 145835

The most straightforward way is to assign the results of Hy and pass them to By:

hy_res = Hy(n)
by_res = By(A = hy_res$A, B = hy_res$B, n = hy_res$n)

# or use with() for a little less typing
by_res = with(hy_res, By(A, B, n))

Since the arguments are in a list, you can also use do.call which calls a function on a set of arguments provided in a list:

by_res = do.call(what = By, args = Hy(n))

Note that functions in R cannot return multiple arguments, so you should probably rewrite the last line of By to be return(list(C, D, E)).

Upvotes: 2

Related Questions