1 + 1
[1] 2
We can write R code directly in the console.
Use R as a calculator to compute 1 + 1
in the console
You can do mathematical calculations in R using the following symbols:
(
, )
^
or **
*
/
+
-
Compute 3 squared in the console
Compute 2 divided by 100,000 in the console
Use the logarithm function log()
to compute the logarithm of 10 in the console
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.
Create a new code chunk and compute 4 times 5
Inside your code chunk, on a new line, add some code to compute 3 squared (3^2
). What do you think will happen when you render your document? Will both lines of code be computed, or just the final one?
4 * 5
[1] 20
3^2
[1] 9
Both lines are computed in the rendered document!
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
).
Can you figure out what the output of the following code chunk will look like (will the code and code comment be shown in the output)?
# two times three
2 * 3
[1] 6
The rendered document will show both the code and the output