[R] Integrating a function that contains for loop or vectorization for for loop

Shaami nz@h@@m @end|ng |rom gm@||@com
Sat Jul 18 05:14:16 CEST 2020


Hi Everyone

It has been a long time I am facing a problem with integrating a function
that contains for-loop or even vectorization of for loop. Could you please
guide for the following MWE that how I could get rid of the error or
warning messages?

My MWE code is here:

myfun <- function(X, a, b){
  k <- 1:10
  term <- a * b * X^k
  fx <- exp(X) * sum(term)
  print(X)
  print(term)
  return(fx)
}

a <- 5
b <- 4
integrate(myfun, lower = 0, upper = 10, a = a, b = b)

If I use the following version of my code, it does not give any error.
However, I am not sure that it is correct.

myfun <- function(X, a, b){
  term <- list()
  for(k in 1:10){
    term[[k]] <- a * b * X^k
  }
  fx <- exp(X) * sum(unlist(term))
  print(X)
  print(term)
  return(fx)
}

a <- 5
b <- 4
integrate(myfun, lower = 0, upper = 10, a = a, b = b)



Thank you

Regrads

	[[alternative HTML version deleted]]



More information about the R-help mailing list