Home > OS >  How to find sum of all of the odd numbers using for loop?
How to find sum of all of the odd numbers using for loop?

Time:10-24

This question for self study. I find it but I stuck when it says return 0 when there is not odd numbers.

CodePudding user response:

oddnumbers <- function(data) {
  sumodd <- c(0)
  for(i in data) {
    if (i %% 2 != 0) {
      sumodd = sumodd   i
    }
  }
  return (sumodd)
}

If you need any explanation, let me know!

CodePudding user response:

R is a vector based language, thus one can avoid the use of loops in many cases with R.

oddnumbers <- function(data) {
   #identify the odd numbers data %%2 !=0
   #identify the index of the odd numbers which(...)
   #filter the odds data[...]
   sum(data[(which(data %%2 !=0))])
}

testdata <- trunc(runif(20, 1, 100))
oddnumbers(testdata)

Using the which() and the built-in vectorized sum() function, will perform about 1000x faster than a R loop.

  •  Tags:  
  • r
  • Related