rnorouzian
rnorouzian

Reputation: 7517

Managing argument input value usage inside an R function

My function foo is meant to compute a variable called d using one of its arguments: s, t, or f.

For example, if a user uses foo(n = 30:35, s = 1:2, t = 3:5, f = 7) I want foo to first compute d using t, then f, and then s. Thus, in the output, I expect 6 ds (i.e., 2 from t, 1 from f, and 2 from s).

I want the the first 2 ns be for t, the next n be for f, and the remaining ns be for s. Is there a way I can mange ns inside the function this way?

foo <- function(n, s = NULL, t = NULL, f = NULL){

d1 <- if(!is.null(t)) t + n else NULL
d2 <- if(!is.null(f)) f^2 + n else NULL

m <- if(!is.null(s)) s/2 + n else NULL
r <- if(!is.null(m)) m + 1 else NULL

d3 <- if(!is.null(m)) m + r else NULL

data.frame(d = c(d1, d2, d3))
}

 # Example of use:
 foo(n = 30:35, s = 1:2, t = 3:5, f = 7)

Upvotes: 0

Views: 54

Answers (1)

akrun
akrun

Reputation: 887991

We can loop through the elements of 't', 'f', 's', add (+) with 'n' and get the output in a list

foo <- function(n, s = NULL, t = NULL, f = NULL){

      dts <-  if(!is.null(t)) sapply(t, `+`, n) else NULL
      dfs <- if(!is.null(f)) sapply(f^2, `+`,  n) else NULL

      ms <- if(!is.null(s)) sapply(s/2, `+`,  n) else NULL
      rs <- if(!is.null(ms)) ms + 1 else NULL

      dss <- if(!is.null(ms)) ms + rs else NULL

      list(t_out =dts, f_out = dfs, s_out = dss)
      }

 # Example of use:
foo(n = 30:35, s = 1:2, t = 3:5, f = 7)

Upvotes: 1

Related Questions