H.S
H.S

Reputation: 11

Function to calculate the sum of 1's in numeric vector gives a wrong result

I want to calculate the number of 1's in a numeric vector. here is my code, It should be 4 but It's 9, there is something wrong with it.

data <- c(1,1,0,0,2,2,1,0,1)
num <- function(x){
n <- length(x)
for (i in 1:n) {
if(x[i]==1) sum1 <- sum(i)
}
return(sum1)
}
num(data)

Upvotes: 1

Views: 82

Answers (2)

Bpendragon
Bpendragon

Reputation: 44

data <- c(1,1,0,0,2,2,1,0,1)
num <- function(x){
  n <- length(x)
  sum1<-0
  for (i in 1:n) {
    if(x[i] == 1){
      sum1<-sum1+1
    } 
  }
return(a)
}  

num(data)

Result:

[1] 4

You appear to be using the sum operator incorrectly, But all you appear to be returning is the index of the last occurrence of 1. What I believe is happening is you are overwriting sum1 every time with the sum of i and 0, and then returning it at the end, if you swap the last two elements in the vector you then get 8 out using your method.

My code I split the if statement and explicitly wrapped its components and used a left assignment operator like the increment function.

I'm sure there's a way to do it more directly, but this way is in my opinion a bit more legible and easier to follow.

Upvotes: 0

John
John

Reputation: 23758

There seem to be a few misunderstandings in the code and I'm not sure how to give a lesson on correction other than example. The short and best R solution to your stated problem would be:

sum( data == 1 )

This works because data == 1 converts to 1 for every TRUE value and 0 for every FALSE when you attempt to treat logicals as numbers. If you don't just want a solution to the described problem but your code fixed up something like the following would work.

num <- function(x){
  n <- length(x)
  sum1 <- 0
  for (i in 1:n) {
    if(x[i]==1) sum1 <- sum1 + 1
  }
  return(sum1)
}

However, for a long vector that function will be spectacularly slow in R. Turning the solution I proposed at the beginning of this post into the function would just be.

num <- function(x) sum( x == 1 )

This function will be very fast for any vector R can hold in memory.

Upvotes: 5

Related Questions