if statement in R can only have one line?
Asked Answered
A

6

31

I was trying a tiny code with if statement, although it is very simple,but there is something I really confused here is the code

n<-857
while(n!=1){
if(n<=0)
 print("please input a positive integer")
else if(n%%2==0)
 n<-n/2
 print(n)
else
 n<-3*n+1
 print(n)
  }

as we see above,when running this code in R, there comes the error,but if I change the if statement like this

if(n<=0)
     print("please input a positive integer")
    else if(n%%2==0)
     n<-n/2
    else
     n<-3*n+1

it is ok ,my question is that can we only write one line under each judgement? if I want to do something more after each judge, what should I do ,just like this case, I want to change the value of n,but also want to display it, what should I do? thank you very much

Amado answered 23/3, 2013 at 12:5 Comment(1)
This looks like you may be coming from python, where whitespace matters. As a general rule, most languages (R, C, Java, javascript) don't care about whitespace. All the tabs, carriage returns, and spaces you can enter don't change a thing. They use brackets {} to group code together into blocks. Existing answers mention this, but not as a general high-level idea.Early
S
76

To be precise, this is not about lines but about statements. You can have the whole if else statement in one line:

> if (TRUE) 1 else 3
[1] 1

A statement will end at the end of the line (if complete), you can see that nicely in interactive mode if you enter the code line by line:

> if (TRUE) 
+ 1
[1] 1
> else
Fehler: Unerwartete(s) 'else' in "else" # error: unexpected 'else' in "else"
> 3
[1] 3

if can come in form if (condition) statement or if (condition) statement else other.statement, the interpreter assumes the first version is meant if the statement is complete after line 2 - in interactive mode it cannot sensibly wait whether an else appears next. This is different in sourced code - there it is clear with the next line which form it is.

Semicolons end statements as well:

> if (TRUE) 1; else 3
[1] 1
Fehler: Unerwartete(s) 'else' in " else"  # error: unexpected 'else' in "else"

But you can only have one statement in each branch of the condition.

> if (TRUE) 1; 2 else 3
[1] 1
Fehler: Unerwartete(s) 'else' in " 2 else" # error: unexpected 'else' in "2 else"

Curly braces group statements so they appear as one statement.

> if (TRUE) {1; 2} else 3
[1] 2
Slushy answered 23/3, 2013 at 13:38 Comment(1)
thank you for your kindly replay, I will continue see the help file, the skill in R is so beautifulAmado
B
12

To group statements, surround them with curly braces as you've done with the while loop:

if(n<=0) {
     print("please input a positive integer")
} else if(n%%2==0) {
     n<-n/2
     print(n)
} else {
     n<-3*n+1
     print(n)
}

This will allow you to place multiple statements inside the if, the else if and the final else.

Beaverette answered 23/3, 2013 at 12:8 Comment(0)
E
12

You have to use {} to allow the if statement to have more than one line. Try this:

n<-857
while(n!=1){
  if(n<=0){
    print("please input a positive integer")
  }
    
  else if(n%%2==0){
    n<-n/2
    print(n)
  }
    else {
      n<-3*n+1
      print(n)
    }
}
Erdmann answered 23/3, 2013 at 12:8 Comment(1)
This only works because it is in a while loop. From the R Language Definition: "When the if statement is not in a block the else, if present, must appear on the same line as the end of statement2. Otherwise the new line at the end of statement2 completes the if and yields a syntactically complete statement that is evaluated. A simple solution is to use a compound statement wrapped in braces, putting the else on the same line as the closing brace that marks the end of the statement."Docia
D
1

while the direct answer is, as has been noted, to use curly braces;
it is worth adding that you can integrate the <- assignment operator into many functions.

In your specific case:

    print(n <- 3*n+1)

   ## instead of 
   #  n <- 3*n+1
   #  print(n)


note that using = here will NOT work. It must be <-

Dominant answered 23/3, 2013 at 13:37 Comment(2)
It isn't a problem for this example, but the assignment will only occur if the argument is actually evaluated in the function. The effect is as if the expression is passed to the function, rather than the value (as it would be in C/C++). Example: g <- function(x) {} ; n <- 1; g(n <- 2); nApivorous
@MatthewLundberg, absolutely. That's why I qualified my statement indicating that it works with many functions. :)Dominant
L
0

Yes, you can use curly braces to contain more than statements for each conditional statement:

if (condition){
    statement 1
    print()
}
else{
    statement 2 
    print()
} 

Addition: if you want to use only if and else statement in one line you can use this:

ifelse(condition, statement1, statement2)
Loginov answered 25/12, 2021 at 19:55 Comment(0)
E
-2

Ever heard of curly barces?

n<-857
while(n!=1){
    if(n<=0) {
        print("please input a positive integer")
    } else if(n%%2==0) {
        n<-n/2
        print(n)
    } else {
        n<-3*n+1
        print(n)
    }
}
Every answered 23/3, 2013 at 12:9 Comment(6)
it looks like this answer has a lot of downvotes. I wonder why that is?Dominant
@RicardoSaporta snarky comment? no explanation? [I didn't downvote by the way] Shame people don't leave comments when they downvote...Widescreen
Thanks for the upvotes. It wasn't meant to come over that snarky. Was probably more a case of fortune(271).Every
right on. Yet, by the very example that the OP gave, s/he clearly has heard of curly braces. The issue is one of knowing how to use them correctly. Guessing by the many downvotes of a seemingly 'technically-correct' answer, it seems that the snarknyness is pretty apparent.Dominant
actually I am a new here , although I know something about the forum, to be honest, I didn't know much about stackoverflow's rule, deep in my heart , I thank you all the people that help me with my problem kindly, may be there is some misunderstanding or mistake, please forgive a new for my possible mistake and operationAmado
@TOPMAD, you are fine. The discussion here is in regards to Henrik's wording of his answer.Dominant

© 2022 - 2024 — McMap. All rights reserved.