1

Can an if statement have more than one then statements?

# this works

a <- c(1,2,3,4,5,6,7,8,9,10)
b <- c(4,3,5,2,8,9,1,2,2,4)
c <- c(9,9,9,5,5,5,2,2,2,1)
for(i in 1:10) { if(c[i]==2) a[i]= 100; if(c[i]==2) b[i]= -99  }


# this does not work

d <- c(1,2,3,4,5,6,7,8,9,10)
e <- c(4,3,5,2,8,9,1,2,2,4)
f <- c(9,9,9,5,5,5,2,2,2,1)
for(i in 1:10) { if(f[i]==2) (d[i]= 100 & e[i]= -99)  }
Martin G
  • 17,357
  • 9
  • 82
  • 98
Mark Miller
  • 12,483
  • 23
  • 78
  • 132
  • 1
    I'm not sure what you're trying to ask. Try only posting the code that you need help with; the first three lines are identical in both code-boxes. – alexyorke Mar 22 '12 at 19:26

3 Answers3

4

You need to have each statement in a separate line (delimited by ;) and the whole execution block enclosed within curly braces

for(i in 1:10) { if(f[i]==2) {d[i]= 100; e[i]= -99}  }
James
  • 65,548
  • 14
  • 155
  • 193
3

You're probably confusing if-expressions (a.k.a. ternary operators) with if-statements. In the latter, you usually have a brace-enclosed block of statements, which are delimited by semicolons or newlines:

R> for(i in 1:10) if(f[i]==2) { d[i]= 100; e[i]= -99 }
R> d
 [1]   1   2   3   4   5   6 100 100 100  10
R> e
 [1]   4   3   5   2   8   9 -99 -99 -99   4

Also, here is a somewhat faster equivalent:

a[which(c==2)] = 100
b[which(c==2)] = -99
Community
  • 1
  • 1
ulidtko
  • 14,740
  • 10
  • 56
  • 88
  • I do not have a more specific problem in mind right now. The issue of multiple 'then' statements with one 'if' is simply something I have wondered about for a long time. I will remember the 'which' approach as well. Thanks to both of you for the outstanding answers. – Mark Miller Mar 22 '12 at 19:46
  • @MarkMiller eh... may I ask you a personal question? Can you tell please, what is your background in programming languages? Is R your first programming language? This is important for me to understand your problem on a more deep level and possibly to improve the R documentation appropriately. – ulidtko Mar 22 '12 at 21:18
  • 1
    I have some experience with Fortran, BASIC, R, C, OpenBUGS and SAS. Currently, I mostly use R, with some OpenBUGS, and I am learning more about C. I develop and publish models. However, I am not an expert in any language. That is why I enjoy this site so much. I hope this helps. – Mark Miller Mar 22 '12 at 21:39
3

Yes you can as others have mentioned. It's also more clear if you place things on new lines and use some indentation convention. For instance I might write your code like

a <- 1:10
b <- c(4, 3, 5, 2, 8, 9, 1, 2, 2, 4)
c <- c(9, 9, 9, 5, 5, 5, 2, 2, 2, 1)
for(i in 1:10){
    if(c[i] == 2){
        a[i] <- 100
        b[i] <- -99
    }
}
Dason
  • 60,663
  • 9
  • 131
  • 148