0

I'm having troubles using several functions within the same one and calling the arguments generated. I'm using a more complicated function that can be simplified as followed:

 func.essai <- function(x) {
 g <- sample(seq(1,30), x)
 i <- sample(x,1)
 func.essai.2 <- function(y,i) {
  z <- y+i
 }
 h <- sapply(g,func.essai.2(y,i))
}
sq <- seq(1,4)
lapply(sq, func.essai)

I'm using arguments that are generated at the beginning of func.essai (and that depend on x) as a fixed input for func.essai.2, here for i, and as a vector to go through on the sapply function, here for g. This code doesn't work as such -- it doesn't recognize y and/or i. How can I rewrite the code to do so?

3
  • What is the expected output? And the variable y is not defined anywhere, is it? Commented Nov 10, 2017 at 17:59
  • A list of the z generated (=y+i) for each value of sq, and each value of g Commented Nov 10, 2017 at 18:02
  • Second argument of sapply must be a function, by adding the parameter (y,i) you're passing the result of the function. Commented Nov 10, 2017 at 18:13

1 Answer 1

1

I think the error you get is because of your use of sapply. This should work instead of your line containing sapply:

 h <- sapply(g,func.essai.2, i)

See ?sapply, which tells you that you should provide additional arguments behind the function that you are applying.

Sign up to request clarification or add additional context in comments.

1 Comment

An alternative would be to use an anonymous function: sapply(g, function(x) func.essai.2(x, i))

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.