0

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)

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, my real function is not going to use + I just used a simple example. But I think I can't achieve what I have in mind. Anyways, thank you so much.
@rnorouzian If it is a complicated funciton, use anonymous function call sapply(t, function(x) yourfunction(x, n))
Arun, is This difficult to achieve?

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.