0

I am not sure I quite understand how to use an if and else statement within a for loop. My code looks like this:

> X
[1] 1 0 1 1 1
A=0
for (i in 1:5){
if (X[i]=1)
A=A+1
}
else{
A=A
}

for example in this case there are 4 '1's in the vector X. So for every 1 in the vector I want it to add 1 to the value of A. (So A should equal 4).

  • It has to be `if(X[i] == 1)`. Additionally your example needs a `{` and a `}`. Your `else` block is useless. What is your question? – sgibb Mar 06 '14 at 21:06
  • 1
    This would be a relatively unusual thing to do in R, I think. The idiomatic way to get what you want is simply `A <- sum(X)`. Does that answer your question? If not, could expand your question? – Matt Parker Mar 06 '14 at 21:06
  • 1
    Or say that X wasn't conveniently kinda Boolean already, e.g. `X <- c("cow", "pig", "cow", "cow", "cow")`. You could get the same count with `A <- sum(X %in% "cow")`. The `X %in% "cow"` comparison creates a logical vector that `sum()` can still add up. – Matt Parker Mar 06 '14 at 21:14

4 Answers4

1

As others have mentioned: = is for assignment (similar to <-; see here for details) and == is to compare equality.

You final loop should be:

for(i in X){
  if (i == 1) A <- A + 1
}

You don't need the else clause because it doesn't really do anything, just slows down the loop slightly.

R is vectorized though so use that fact. It is more idiomatic to say:

sum(X)

if you want to count them all up or look at apply and lapply for more complex situations, depending on the context of what you are doing.

Community
  • 1
  • 1
Christopher Louden
  • 7,540
  • 2
  • 26
  • 29
0
X <- c(1, 0, 1, 1, 1)
A <- 0

for (i in X){
   if (i == 1)
    A <- A + 1
   else A <- A + 0
}
maloneypatr
  • 3,562
  • 4
  • 23
  • 33
0

This is what you are after:

for (i in 1:5){
  if (X[i]==1){
    A=A+1
  }else{
    A=A  
  }
}

Notice the double = sign in X[i]==1gives you your falsifiable boolean statement (does X[i] equal 1), compared to the single = sign in your example which sets X[i] equal to 1

drJones
  • 1,233
  • 1
  • 16
  • 24
  • 1
    You've got to be careful with `==`, though - if `X` contained any `NA`s, this would throw an error. `%in%` is safer, to the point that I almost never use `==` at all. – Matt Parker Mar 06 '14 at 21:17
0

The comparison sign should be (X[i]==1) and the way you are using the if statement is fine. But you got extra braces which is messing up your code.

it should look like this

X <- c(1,0,1,1,1)
A=0
for (i in 1:5){
    if (X[i]==1)
        A=A+1
    else
        A=A
}

or like this

X <- c(1,0,1,1,1)
A=0
for (i in 1:5){
    if (X[i]==1){
        A=A+1
    }
    else{
        A=A
    }
}

If you have just one instruction within an if statement you don't need the braces, but if more two or more instructions will run for a certain condition the braces are necessary.

The indentation is there only to help the visualisation.

mrcl
  • 2,130
  • 14
  • 29