Sunday, July 29, 2012

Control Flow

I use if/else and for quite often, but rarely use while or repeat.  Even still, there are a couple of things with if/else that give me trouble if I haven't used it in a while.

If everything is on one line, all is good:

> x = 1
> y = if(x>0) 1 else 0
> y
[1] 1

But if I put the curly braces in the wrong place:

> if(x>0) {
+   x = -x
+   y = 1
+ }
> else {
Error: unexpected 'else' in "else"
>   x = x
>   y = 0
> }
Error: unexpected '}' in "}"

So I have to always make sure to do this:

> if(x>0) {
+   x = -x
+   y = 1
+ } else {
+   x = x
+   y = 0
+ }
> x
[1] -1
> y
[1] 1

No comments:

Post a Comment