takeITeasy
takeITeasy

Reputation: 360

user build function in R with integrated for-loop

d <- function(...){
    x <- list(...) # THIS WILL BE A LIST STORING EVERYTHING:
    for(n in x){
      n*n+5       # Example of inbuilt function
    } %>%
      sum(.)
}

d(4,3)

based on Creating a function in R with variable number of arguments, and the answer by @Onyambu

35 should be the result
(4 * 4+5)+(3 * 3+5)=21+14=35.
However, there is no error message and R does not show me no result at all.

Upvotes: 1

Views: 51

Answers (2)

Ric S
Ric S

Reputation: 9277

The main issue is that you have to store the output of your for-loop somewhere. The variable s takes the output of the loop and is returned at the end. In order to obtain your desired output (35) you can do something like

d <- function(...){
  x <- list(...)
  s <- 0
  for(n in x)
    s <- s + n*n+5       
  s
}

d(4,3)
# [1] 35

Upvotes: 4

Ronak Shah
Ronak Shah

Reputation: 389325

Your function can be vectorized so you don't need for loop :

d <- function(...){
   x <- c(...) 
   sum(x * x + 5)
}
d(4, 3)
#[1] 35

Upvotes: 4

Related Questions