<- 1
x print(x)
[1] 1
x
[1] 1
<- "hello" msg
This lecture, as the rest of the course, is adapted from the version Stephanie C. Hicks designed and maintained in 2021 and 2022. Check the recent changes to this file through the GitHub history.
Before class, you can prepare by reading the following materials:
Material for this lecture was borrowed and adopted from
At the end of this lesson you will:
At the R prompt we type expressions. The <-
symbol is the assignment operator.
The grammar of the language determines whether an expression is complete or not.
Error: <text>:2:0: unexpected end of input
1: x <- ## Incomplete expression
^
The #
character indicates a comment.
Anything to the right of the #
(including the #
itself) is ignored. This is the only comment character in R.
Unlike some other languages, R does not support multi-line comments or comment blocks.
When a complete expression is entered at the prompt, it is evaluated and the result of the evaluated expression is returned.
The result may be auto-printed.
The [1]
shown in the output indicates that x
is a vector and 5
is its first element.
Typically with interactive work, we do not explicitly print objects with the print()
function; it is much easier to just auto-print them by typing the name of the object and hitting return/enter.
However, when writing scripts, functions, or longer programs, there is sometimes a need to explicitly print objects because auto-printing does not work in those settings.
When an R vector is printed you will notice that an index for the vector is printed in square brackets []
on the side. For example, see this integer sequence of length 20.
The numbers in the square brackets are not part of the vector itself, they are merely part of the printed output.
With R, it’s important that one understand that there is a difference between the actual R object and the manner in which that R object is printed to the console.
Often, the printed output may have additional bells and whistles to make the output more friendly to the users. However, these bells and whistles are not inherently part of the object.
The most basic type of R object is a vector.
There is really only one rule about vectors in R, which is that
A vector can only contain objects of the same class
To understand what we mean here, we need to dig a little deeper. We will come back this in just a minute.
There are two types of vectors in R:
Atomic vectors:
FALSE
, TRUE
, and NA
Lists, which are sometimes called recursive vectors because lists can contain other lists.
[Source: R 4 Data Science]
There’s one other related object: NULL.
NA
which is used to represent the absence of a value in a vector).Empty vectors can be created with the vector()
function.
The c()
function can be used to create vectors of objects by concatenating things together.
In the above example, T
and F
are short-hand ways to specify TRUE
and FALSE
.
However, in general, one should try to use the explicit TRUE
and FALSE
values when indicating logical values.
The T
and F
values are primarily there for when you’re feeling lazy.
So, I know I said there is one rule about vectors:
A vector can only contain objects of the same class
But of course, like any good rule, there is an exception, which is a list (which we will get to in greater details a bit later).
For now, just know a list is represented as a vector but can contain objects of different classes. Indeed, that’s usually why we use them.
The main difference between atomic vectors and lists is that atomic vectors are homogeneous, while lists can be heterogeneous.
Integer and double vectors are known collectively as numeric vectors.
In R, numbers are doubles by default.
To make an integer, place an L
after the number:
The distinction between integers and doubles is not usually important, but there are two important differences that you should be aware of:
Numbers in R are generally treated as numeric objects (i.e. double precision real numbers).
This means that even if you see a number like “1” or “2” in R, which you might think of as integers, they are likely represented behind the scenes as numeric objects (so something like “1.00” or “2.00”).
This isn’t important most of the time…except when it is!
If you explicitly want an integer, you need to specify the L
suffix. So entering 1
in R gives you a numeric object; entering 1L
explicitly gives you an integer object.
There is also a special number Inf
which represents infinity. This allows us to represent entities like 1 / 0
. This way, Inf
can be used in ordinary calculations; e.g. 1 / Inf
is 0.
The value NaN
represents an undefined value (“not a number”); e.g. 0 / 0; NaN
can also be thought of as a missing value (more on that later)
R objects can have attributes, which are like metadata for the object.
These metadata can be very useful in that they help to describe the object.
For example, column names on a data frame help to tell us what data are contained in each of the columns. Some examples of R object attributes are
Attributes of an object (if any) can be accessed using the attributes()
function. Not all R objects contain attributes, in which case the attributes()
function returns NULL
.
However, every vector has two key properties:
typeof()
. [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
[20] "t" "u" "v" "w" "x" "y" "z"
[1] "character"
[1] 1 2 3 4 5 6 7 8 9 10
[1] "integer"
length()
.There are occasions when different classes of R objects get mixed together.
Sometimes this happens by accident but it can also happen on purpose.
Why is this happening?
In each case above, we are mixing objects of two different classes in a vector.
But remember that the only rule about vectors says this is not allowed?
When different objects are mixed in a vector, coercion occurs so that every element in the vector is of the same class.
In the example above, we see the effect of implicit coercion.
What R tries to do is find a way to represent all of the objects in the vector in a reasonable fashion. Sometimes this does exactly what you want and…sometimes not.
For example, combining a numeric object with a character object will create a character vector, because numbers can usually be easily represented as strings.
Objects can be explicitly coerced from one class to another using the as.*()
functions, if available.
[1] "integer"
[1] 0 1 2 3 4 5 6
[1] FALSE TRUE TRUE TRUE TRUE TRUE TRUE
[1] "0" "1" "2" "3" "4" "5" "6"
Sometimes, R can’t figure out how to coerce an object and this can result in NA
s being produced.
Warning: NAs introduced by coercion
[1] NA NA NA
[1] NA NA NA
When nonsensical coercion takes place, you will usually get a warning from R.
Matrices are vectors with a dimension attribute.
[,1] [,2] [,3]
[1,] NA NA NA
[2,] NA NA NA
[1] 2 3
$dim
[1] 2 3
Matrices are constructed column-wise, so entries can be thought of starting in the “upper left” corner and running down the columns.
Matrices can also be created directly from vectors by adding a dimension attribute.
[1] 1 2 3 4 5 6 7 8 9 10
[,1] [,2] [,3] [,4] [,5]
[1,] 1 3 5 7 9
[2,] 2 4 6 8 10
Matrices can be created by column-binding or row-binding with the cbind()
and rbind()
functions.
Lists are a special type of vector that can contain elements of different classes. Lists are a very important data type in R and you should get to know them well.
Lists, in combination with the various “apply” functions discussed later, make for a powerful combination.
Lists can be explicitly created using the list()
function, which takes an arbitrary number of arguments.
We can also create an empty list of a prespecified length with the vector()
function
Factors are used to represent categorical data and can be unordered or ordered. One can think of a factor as an integer vector where each integer has a label.
Factors are important in statistical modeling and are treated specially by modelling functions like lm()
and glm()
.
Using factors with labels is better than using integers because factors are self-describing.
Having a variable that has values “Yes” and “No” or “Smoker” and “Non-Smoker” is better than a variable that has values 1 and 2.
Factor objects can be created with the factor()
function.
[1] yes yes no yes no
Levels: no yes
x
no yes
2 3
[1] 2 2 1 2 1
attr(,"levels")
[1] "no" "yes"
Often factors will be automatically created for you when you read in a dataset using a function like read.table()
.
The order of the levels of a factor can be set using the levels
argument to factor()
. This can be important in linear modeling because the first level is used as the baseline level.
Missing values are denoted by NA
or NaN
for undefined mathematical operations.
is.na()
is used to test objects if they are NA
is.nan()
is used to test for NaN
NA
values have a class also, so there are integer NA
, character NA
, etc.
A NaN
value is also NA
but the converse is not true
Data frames are used to store tabular data in R. They are an important type of object in R and are used in a variety of statistical modeling applications. Hadley Wickham’s package dplyr has an optimized set of functions designed to work efficiently with data frames.
Data frames are represented as a special type of list where every element of the list has to have the same length.
Unlike matrices, data frames can store different classes of objects in each column. Matrices must have every element be the same class (e.g. all integers or all numeric).
In addition to column names, indicating the names of the variables or predictors, data frames have a special attribute called row.names
which indicate information about each row of the data frame.
Data frames are usually created by reading in a dataset using the read.table()
or read.csv()
. However, data frames can also be created explicitly with the data.frame()
function or they can be coerced from other types of objects like lists.
foo bar
1 1 TRUE
2 2 TRUE
3 3 FALSE
4 4 FALSE
[1] 4
[1] 2
$names
[1] "foo" "bar"
$class
[1] "data.frame"
$row.names
[1] 1 2 3 4
Data frames can be converted to a matrix by calling data.matrix()
. While it might seem that the as.matrix()
function should be used to coerce a data frame to a matrix, almost always, what you want is the result of data.matrix()
.
foo bar
[1,] 1 1
[2,] 2 1
[3,] 3 0
[4,] 4 0
$dim
[1] 4 2
$dimnames
$dimnames[[1]]
NULL
$dimnames[[2]]
[1] "foo" "bar"
Let’s use the palmerpenguins
dataset.
penguins
have?penguins
R object?species
column in the penguins
dataset?bill_length_mm
, bill_depth_mm
, flipper_length_mm
, and body_mass_g
# A tibble: 344 × 8
species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
<fct> <fct> <dbl> <dbl> <int> <int>
1 Adelie Torgersen 39.1 18.7 181 3750
2 Adelie Torgersen 39.5 17.4 186 3800
3 Adelie Torgersen 40.3 18 195 3250
4 Adelie Torgersen NA NA NA NA
5 Adelie Torgersen 36.7 19.3 193 3450
6 Adelie Torgersen 39.3 20.6 190 3650
7 Adelie Torgersen 38.9 17.8 181 3625
8 Adelie Torgersen 39.2 19.6 195 4675
9 Adelie Torgersen 34.1 18.1 193 3475
10 Adelie Torgersen 42 20.2 190 4250
# ℹ 334 more rows
# ℹ 2 more variables: sex <fct>, year <int>
R objects can have names, which is very useful for writing readable code and self-describing objects.
Here is an example of assigning names to an integer vector.
NULL
New York Seattle Los Angeles
1 2 3
[1] "New York" "Seattle" "Los Angeles"
$names
[1] "New York" "Seattle" "Los Angeles"
Lists can also have names, which is often very useful.
$`Los Angeles`
[1] 1
$Boston
[1] 2
$London
[1] 3
[1] "Los Angeles" "Boston" "London"
Matrices can have both column and row names.
c d
a 1 3
b 2 4
Column names and row names can be set separately using the colnames()
and rownames()
functions.
For data frames, there is a separate function for setting the row names, the row.names()
function.
Also, data frames do not have column names, they just have names (like lists).
So to set the column names of a data frame just use the names()
function. Yes, I know its confusing.
Here’s a quick summary:
Object | Set column names | Set row names |
---|---|---|
data frame | names() |
row.names() |
matrix | colnames() |
rownames() |
There are a variety of different builtin-data types in R. In this chapter we have reviewed the following
All R objects can have attributes that help to describe what is in the object. Perhaps the most useful attribute is names, such as column and row names in a data frame, or simply names in a vector or list. Attributes like dimensions are also important as they can modify the behavior of objects, like turning a vector into a matrix.
Here are some post-lecture questions to help you think about the material discussed.
Describe the difference between is.finite(x) and !is.infinite(x).
A logical vector can take 3 possible values. How many possible values can an integer vector take? How many possible values can a double take? Use google to do some research.
What functions from the readr package allow you to turn a string into logical, integer, and double vector?
Try and make a tibble that has columns with different lengths. What happens?
─ Session info ───────────────────────────────────────────────────────────────────────────────────────────────────────
setting value
version R version 4.3.1 (2023-06-16)
os macOS Ventura 13.5
system aarch64, darwin20
ui X11
language (EN)
collate en_US.UTF-8
ctype en_US.UTF-8
tz America/New_York
date 2023-08-17
pandoc 3.1.5 @ /opt/homebrew/bin/ (via rmarkdown)
─ Packages ───────────────────────────────────────────────────────────────────────────────────────────────────────────
package * version date (UTC) lib source
cli 3.6.1 2023-03-23 [1] CRAN (R 4.3.0)
colorout 1.2-2 2023-05-06 [1] Github (jalvesaq/colorout@79931fd)
colorspace 2.1-0 2023-01-23 [1] CRAN (R 4.3.0)
digest 0.6.33 2023-07-07 [1] CRAN (R 4.3.0)
dplyr * 1.1.2 2023-04-20 [1] CRAN (R 4.3.0)
evaluate 0.21 2023-05-05 [1] CRAN (R 4.3.0)
fansi 1.0.4 2023-01-22 [1] CRAN (R 4.3.0)
fastmap 1.1.1 2023-02-24 [1] CRAN (R 4.3.0)
forcats * 1.0.0 2023-01-29 [1] CRAN (R 4.3.0)
generics 0.1.3 2022-07-05 [1] CRAN (R 4.3.0)
ggplot2 * 3.4.3 2023-08-14 [1] CRAN (R 4.3.1)
glue 1.6.2 2022-02-24 [1] CRAN (R 4.3.0)
gtable 0.3.3 2023-03-21 [1] CRAN (R 4.3.0)
hms 1.1.3 2023-03-21 [1] CRAN (R 4.3.0)
htmltools 0.5.6 2023-08-10 [1] CRAN (R 4.3.0)
htmlwidgets 1.6.2 2023-03-17 [1] CRAN (R 4.3.0)
jsonlite 1.8.7 2023-06-29 [1] CRAN (R 4.3.0)
knitr 1.43 2023-05-25 [1] CRAN (R 4.3.0)
lifecycle 1.0.3 2022-10-07 [1] CRAN (R 4.3.0)
lubridate * 1.9.2 2023-02-10 [1] CRAN (R 4.3.0)
magrittr 2.0.3 2022-03-30 [1] CRAN (R 4.3.0)
munsell 0.5.0 2018-06-12 [1] CRAN (R 4.3.0)
palmerpenguins * 0.1.1 2022-08-15 [1] CRAN (R 4.3.0)
pillar 1.9.0 2023-03-22 [1] CRAN (R 4.3.0)
pkgconfig 2.0.3 2019-09-22 [1] CRAN (R 4.3.0)
purrr * 1.0.2 2023-08-10 [1] CRAN (R 4.3.0)
R6 2.5.1 2021-08-19 [1] CRAN (R 4.3.0)
readr * 2.1.4 2023-02-10 [1] CRAN (R 4.3.0)
rlang 1.1.1 2023-04-28 [1] CRAN (R 4.3.0)
rmarkdown 2.24 2023-08-14 [1] CRAN (R 4.3.1)
rstudioapi 0.15.0 2023-07-07 [1] CRAN (R 4.3.0)
scales 1.2.1 2022-08-20 [1] CRAN (R 4.3.0)
sessioninfo 1.2.2 2021-12-06 [1] CRAN (R 4.3.0)
stringi 1.7.12 2023-01-11 [1] CRAN (R 4.3.0)
stringr * 1.5.0 2022-12-02 [1] CRAN (R 4.3.0)
tibble * 3.2.1 2023-03-20 [1] CRAN (R 4.3.0)
tidyr * 1.3.0 2023-01-24 [1] CRAN (R 4.3.0)
tidyselect 1.2.0 2022-10-10 [1] CRAN (R 4.3.0)
tidyverse * 2.0.0 2023-02-22 [1] CRAN (R 4.3.0)
timechange 0.2.0 2023-01-11 [1] CRAN (R 4.3.0)
tzdb 0.4.0 2023-05-12 [1] CRAN (R 4.3.0)
utf8 1.2.3 2023-01-31 [1] CRAN (R 4.3.0)
vctrs 0.6.3 2023-06-14 [1] CRAN (R 4.3.0)
withr 2.5.0 2022-03-03 [1] CRAN (R 4.3.0)
xfun 0.40 2023-08-09 [1] CRAN (R 4.3.0)
yaml 2.3.7 2023-01-23 [1] CRAN (R 4.3.0)
[1] /Library/Frameworks/R.framework/Versions/4.3-arm64/Resources/library
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────