The purpose of this tutorial is to introduce the preliminaries of coding in R.
My goal is to give you just what you need to begin working with data.
1. Like any programming language, you can do basic math in R.
2. The following code calculates the value of this expression \(e^{0.01} - 1\).
exp(0.01) - 1
[1] 0.01005017
3. The following code calculates the square root of 252.
sqrt(252)
[1] 15.87451
Code Challenge: Calculate the value of: one plus eight percent raised to the seventh power.
1. You can assign data values to variables, which is often useful in data analysis.
x <- exp(0.01) - 1
x
[1] 0.01005017
2. Let’s do some more variable assignment, just for practice.
x <- "SPY"
symbol <- "IWM"
price <- 155.75
vol <- 0.16
x; symbol; price; vol
[1] "SPY"
[1] "IWM"
[1] 155.75
[1] 0.16
Observations:
We didn’t have to declare data types for variables before assigning.
Notice that x
was initially assigned to the number 0.01005
in the previous code block. We then I reassigned it to the character "SPY"
.
This is a feature of R, you can assign and reassign to variables freely.
This flexibility makes R well suited for data analysis.
1. vectors
are the simplest kinds of variables in R.
2. The three variables we just created - symbol
, price
, and vol
- are all vectors
of length one.
3. When vectors
are numeric, you can think of them like the vectors from linear algebra.
4. We use the c()
function to manually create vectors.
symbols <- c("SPY", "QQQ", "IWM", "DIA")
prices <- c(287.50, 182.48, 171.59, 257.85)
symbols; prices
[1] "SPY" "QQQ" "IWM" "DIA"
[1] 287.50 182.48 171.59 257.85
5. Vectors are atomic, which means that all their components have to be of the same data type: character, number, date, etc.
1. vectors
are the building blocks of data.frames
.
2. data.frames
are the workhorse for data analysis in R.
3. A data.frame
is a representation of a rectangle of data, consisting of rows and columns.
4. A column of a data.frame
is a vector
.
R4DS - Chapter 4 - Workflow Basics
R4DS - 20.1 - Introduction
R4DS - 20.2 - Vector basics
R4DS - 20.3 - Important types of atomic vectors
R4DS - 20.4 - Using atomic vectors