learnlifelong
learnlifelong

Reputation: 53

Basic R programming error

count1 should return the first position of 1 in the input. My code is not working. what is the mistake?

count1 <- function(x) {
    for(i in x) {
      if(i==1) break
    }
   i
}
count1(c(2,3,1,4))
[1] 1
count1(c(2,3,1,4,1,4,5,1))
[1] 1

I used same logic to write oddcount which counts the number of odd numbers. However, below code words but count1 does not

> oddcount <- function(x)  {
    k<-0
    for(i in x) {
    if(i%%2==1) k <- k+1
       }
    k
  }
> oddcount(c(1,3,4,5))
[1] 3

Upvotes: 1

Views: 91

Answers (1)

Vincent Bonhomme
Vincent Bonhomme

Reputation: 7453

These two functions are enough for the job:

# returning the 1st position of 1
which_1 <- function(x){
  which.max(x==1)
}

which_1(c(2,3,1,1,5))
[1] 3

# counting the number of odd nb
count_odd <- function(x){
  sum(x%%2 == 0)
}
count_odd(c(2,3,1,1,4))
[1] 2

Edit: Thanks David for pointing the typo!

Upvotes: 4

Related Questions