Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference in using a semicolon or explicit new line in R code

Tags:

r

I originally thought that the semicolon ; was the equivalent to adding an explicit new line, e.g.

x <- 1; y <- 2

is the same as

x <- 1
x <- 2

Certainly the R documentation doesn't seem to make a distinction with respect to syntactically complete statements:

Both semicolons and new lines can be used to separate statements. A semicolon always indicates the end of a statement while a new line may indicate the end of a statement. If the current statement is not syntactically complete new lines are simply ignored by the evaluator.

However, I found that at least in Rstudio Server, the semicolon behaves differently to a new line. For example:

> temp_a ; temp_b <- 1 ; temp_c <- 2
Error: object 'temp_a' not found
> exists("temp_b")
[1] FALSE
> exists("temp_c")
[1] FALSE

compared to

> temp_a
Error: object 'temp_a' not found
> temp_b <- 1
> temp_c <- 2
> 
> exists("temp_b")
[1] TRUE
> exists("temp_c")
[1] TRUE

Why does this happen? Are there any other gotchas I should look out for?

like image 510
Alex Avatar asked Feb 27 '15 05:02

Alex


People also ask

What is semicolon code?

The Semicolon lets the compiler know that it's reached the end of a command. Semicolon is often used to delimit one bit of C++ source code, indicating it's intentionally separated from the respective code.

Why would someone use a semi colon when writing a JavaScript?

Semicolons are an essential part of JavaScript code. They are read and used by the compiler to distinguish between separate statements so that statements do not leak into other parts of the code.


1 Answers

At the console, the script is evaluated as soon as the a line ends with a complete statement. Hence, this:

temp_a 
temp_b <- 1 
temp_c <- 2

is equivelent to calling this:

source(textConnection('temp_a'))
source(textConnection('temp_b <- 1'))
source(textConnection('temp_c <- 2'))

in which each line is evaluated as soon as it is encountered, and failures in previous lines don't prevent the subsequent lines from being evaluated. On the other hand. this:

temp_a ; temp_b <- 1 ; temp_c <- 2

is equivalent to calling this:

source(textConnection('temp_a ; temp_b <- 1 ; temp_c <- 2'))

which is equivalent to this

source(textConnection('
temp_a  
temp_b <- 1 
temp_c <- 2'))

because when first line fails, the remainder of the code is not run.

Incidentally, if you want to mimic this behavior at the console, you can take advantage of the fact that the lines are not evaluated until they make a complete statement, by surrounding the three lines with braces to make a single code block that is evaluated as a whole, like so:

{
    temp_a 
    temp_b <- 1 
    temp_c <- 2
}
like image 105
Jthorpe Avatar answered Oct 14 '22 00:10

Jthorpe