2

I have two functions:

getTotalBL <- function(Ne, n){
  ...
  total_branch_length #output
}


getSNPnumber <- function(total_branch_length,mu,L){


}

Where the total_branch_length in getSNPnumber is the output of the first function (getTotalBL) Do I need to do something more than write the same name of the output or is it correct this way?

2 Answers 2

3

You need to store the output of getTotalBL in an object and pass that on as a function argument to getSNPnumber. The scope of total_branch_length is restricted to getTotalBL.

Here are two examples to demonstrate:

Possibility 1:

f1 <- function(x) x^2;
f2 <- function(xsquared, b) xsquared + b;

f2(f1(2), 1)
#[1] 5

which is the same as

ret_from_f1 <- f1(2);
f2(ret_from_f1, 1);
#[1] 5

Possibility 2:

We can also have a function as an argument of another function (here f2):

f2 <- function(fct, x, b) fct(x) + b;
f2(f1, 2, 1) 
#[1] 5
Sign up to request clarification or add additional context in comments.

1 Comment

Thank youuuuuu so much !
1

If all you're interested in is transferring the results from one function into another, I'd like to suggest the %>% function; it lets you pipe/chain results from one command into another.

It's available in packages magrittr (ordplyr if you're already using tidyverse).

Reusing the above 'Possibility 1'

f1 <- function(x) x^2;
f2 <- function(xsquared, b) xsquared + b;

require(dplyr)
f1(2) %>% f2(1)

UPDATE: Why %>% is useful

To my extremely limited knowledge, R stores all objects in RAM. When you create objects, only for them to be removed, they are still created in RAM. Using %>% lets you bypass this.

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.