Why do the closing and opening brackets ({ and }) of R if statments have to be in this complex multiple line format instead of a simple, single line format?

beginner to R and programming in general. Currently taking a beginner's course and was just wondering why an if statment had to be in this format:

if (nrow(recent_grads) > 1000) { 
    data_size <- "Large" 
    } else {
        data_size <- "Small"

where the { and } characters have to be on seperate lines, as opposed to something more simple such as:

if (nrow(recent_grads) > 1000) { data_size <- "Large" }
  else {data_size <- "Small”}

Thanks for the help in advance.

My understanding of the rules for if statements is as follows. Brackets are used to enclose multiple statements. If you only have a single statement in the if and the else, as in your case, the brackets are not required. If there is a right bracket, }, before the else, it must be on the same line as the else. All of the following work

if (x > 1000) data_size <- "Large" else  data_size <- "Small"

if (x > 1000) {data_size <- "Large"} else  data_size <- "Small"

if (x > 1000) {data_size <- "Large"
  } else  data_size <- "Small"

Thank you FJCC! I just wanted to clarify, what did you mean by 'multiple statements' in the if statement and could you give an example?

They can be in one line if you want. It's just a standard in the coding world for readability, not exclusive to R. I have different standards for myself, but when in a collaborative team, I use lintr (code linter for R).

You can see some sample code below in other languages and you'll see that they are formatted similarly.


1 Like

Here is an example of an if statement containing multiple statements.

if (x > 1000) {
  data_size <- "Large"
  data_color <- "red"
  data_shape = "round"
  } else  {
  data_size <- "Small"
  data_color <- "blue"
  data_shape = "square"

Both the if and the else set the value of three variables.

1 Like

Great, thank you so much!! I understand now : )

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.