Intro to Data Analytics
Corresponds to IDS 2.1-2.3
Creating new files (R script and Quarto)
R as a calculator
Code chunks
Objects
Functions
sum()
c() Combine values into a vector or list
sort()
seq() Create sequence
First, open up your RStudio project folder (e.g, data121)…
In your course RStudio project:
Create a new folder for in-class activities and notes: /activities
Create a new R script file Rbasics_1_activity.R
Create a Quarto Document file Rbasics_1_activity.qmd
Try typing the following in your R script file, one line at a time:
3+4
3*12
2/5
3^2
log(4)
sqrt(34)
Prepare to run the code by either placing your cursor on the line where you have entered your code OR by highlighting the code. To run the code:
OPTION 1: click Run on the toolbar just above your code in the Editor pane.
OPTION 2: use the key command:
Mac: Command + Enter
Windows: Control + Enter
In your Quarto document, create a new code chunk and run a few basic calculations (addition, subtraction, multiplication, division, etc.)
There are a few ways to create code chunks in RStudio:
In the Console type and hit Enter to run:
x <- 3
y <- 4
x <- x + 1
In your R script file type and run:
apples <- 5
pears <- 9
x <- apples + pears
This is a code chunk to practice creating objects as a comment in the first line of the code chunk. Make a comment using the # symbol.x <- 5 + 4
y <- sqrt(72)
z <- apples + pears
Answer <- x + y * z
Finally, enter the function ls() at the end of your code chunk to print out all objects you have created. You can also find these in the Environment pane.
Functions in R are like imperative sentences (e.g. “go”,“stay”, or “sleep”).
Telling R to use a function is described as “calling” a function.
Call a function by typing it’s name followed by two parentheses log().
You can create your own functions (later in the semester).
Create a new code chunk in your Quarto.
Add a comment in the top line.
Type in the sum() function. Run the code chunk.
Use the sum() function to add up two numbers, by adding two arguments inside the function: sum(12, 3)
Arguments specify the “what” or the “how” to a function.
Create a new code chunk in your Quarto.
Add a comment in the top line Prepare a vector to use with the sequence function.
Use the c() function to create a vector of the forecast high temperatures for the next 10 days in Red Hook, NY:
c(79, 78, 72, 69, 74, 79, 80, 80, 78, 76)
temps using <-sort function to order the vector from lowest to highest:sort(temps)
Create a new code chunk in your Quarto.
Add a comment in the top line Calling the sequence function.
Use the seq() function to create a sequence of all numbers between 1 to 20.
seq(1, 20)
seq() function to create a sequence of all even numbers between 1 to 50.seq(1, 50, by = 2)