lundi 13 mai 2019

Managing if statements when length of input value is unkown in R functions

I have two R functions. The first one produces a data.frame. The first column of this output is used inside the second function.

Specifically, the second function takes the argument long which can be any numeric vector e.g. 2, 2, 3 of any length. Then, the function assigns an element from the first column of the first function's outputted data.frame.

For example, if long = c(1, 3, 2), then second function assigns the first element of the first function's output to 1, if 2 the second element of the first function and so on.

Q: Argument long can be of any length, how can I mange the required if statements? (see second function below)?

## First function: #==================================

reg <- function(steps, r){

  x <- diag(steps+1)
  data.frame(r^abs(row(x)-col(x)))
}

## Second function: #==================================

foo <- function(long = c(1, 3, 2), r = .5){

g <- reg(max(long, na.rm = T), r)[,1][-1]  ## from the first function

r <- if(long == 1)  g[1] else if(long == 2) g[2] ## if . . . how many if needed?
return(r)
}  

Aucun commentaire:

Enregistrer un commentaire