1 + 1
[1] 2
We can write R code directly in the console.
You can do mathematical calculations in R using the following symbols:
(
, )
^
or **
*
/
+
-
The problem with only ever writing your R code in the console is that once you quit RStudio, there will be no record of the code that you ran.
Writing your code in a quarto help you to save your code and results in a reproducible way AND communicate your findings to other people.
In a quarto document, like this one, you will write your r code in “code chunks” like this box below:
For example, you can ask R to compute 1+1:
1 + 1
[1] 2
You can view the “output” (result) of your code by either (a) rendering your quarto document, or (b) running your code in the console.
Question: Why is there a [1]
before the output ([1] 2
)? This is just specifying that 2
is the first “entry” of the output.
Solution:
4 * 5
[1] 20
Solution:
4 * 5
[1] 20
3^2
[1] 9
R will ignore any text that follows a #
symbol, so we can add “comments” to our code using #
to make it easier to understand.
# compute 4 times 5
4 * 5
[1] 20
# compute 3 squared
3^2
[1] 9
Take a look at the following code chunk.
What do you think this code chunk will look like in the rendered html document?
[1] 4
This #|
syntax at the beginning of a code chunk corresponds to various options for when the code chunk is “rendered” into html (or pdf).
#| echo: false
hides the code from the html output file, while still showing the output ([1] 4
).