# This is a code chunk!
1.1: Introduction to RStudio
Learning Outcomes
- Students will be able to describe what computer programming languages (code) are, with R as an example.
- Students will be able to describe the role of RStudio in programming with R.
- Students will be able to describe the utility of each panel in RStudio.
- Students will be able to perform basic math functions in the R console.
Rstudio Mini-Tour
Sign up for RStudio
Perform a live-coding mini-tour of RStudio. - edit this section maybe
- What do the different panels do?
- Console versus a script/Rmarkdown file
Using R as a Calculator
Using the Console
You can do basic math in the Console (the bottom left part of the screen). The Console only understands R code, but it can also be treated as a calculator! Hence, we can type in some numbers and mathematical symbols.
Try multiplying 5 and 3 in the Console (hint: * means multiply). Hit Enter
to run that line of code.
R Markdown and Code Chunks
R Markdown (.Rmd) is a file format that lets us incorporate text and code into one document seamlessly. In fact, it is the file format for this document!
- For writing text, you can type as you normally would.
- Code chunks are a bit different:
- Near the top right of your screen you can toggle between viewing this document as under Source or Visual.
- If you view this document under Source, you will see that all code chunks are sandwiched between ”
```{r}
” and ”```
“. - But under Visual, you can type R code in the lines under
{r}
. - To include text in chunks, you will need to put a
#
in front. R will not read anything in the line after#
as code.
Code chunks look like this:
A quick shortcut for adding a code chunk is Ctrl + Alt + i
(Cmd + Opt + i
on a Mac).
Alternatively, you can go to Code > Insert Chunk.
To run a chunk of code, click the green arrow on the top right corner of the chunk.
You can also run one or a few lines of code at a time by having your cursor on the line or highlighting multiple lines and hitting Ctrl
+ Enter
(or Cmd
+ Enter
on a Mac).
Some Code Chunk Practice
Let’s work with an example code chunk.
# I am adding a comment to my code here.
432 - 11 # subtraction
[1] 421
12 + 18 # addition
[1] 30
8 / 4 # division
[1] 2
3 * 5 # multiplication
[1] 15
Notice that if you run code in the Console rather than the code chunk in an R Markdown (.Rmd) file, you don’t need to add the {r}
to tell it that you are typing R code. The Console only understands R code anyway, so we don’t need to tell it what it is!
Math: Small Group Challenge
Write a line of code to raise 2 to the 3rd power (often represented as \(2^3\)). This will likely require a little bit of Googling to figure out.
First, write and run the code in the console.
Next, write and run the code in the code chunk below. What did you have to do differently?
# 1) Console: 2^3 + Enter
# 2) Code chunk: 2^3 + Green arrow *OR* 2^3 + Ctrl + Shift
2^3
[1] 8