Data Structures
- Create and print a vector.
v <- c(1, 2, 3);
v
## [1] 1 2 3
- Create and print a sequence.
s <- 1:5
s
## [1] 1 2 3 4 5
- Create and print a matrix.
m <- matrix(
data = 1:6,
nrow = 2,
ncol = 3)
m
## [,1] [,2] [,3]
## [1,] 1 3 5
## [2,] 2 4 6
- Create and print an array.
a <- array(
data = 1:8,
dim = c(2, 2, 2))
a
## , , 1
##
## [,1] [,2]
## [1,] 1 3
## [2,] 2 4
##
## , , 2
##
## [,1] [,2]
## [1,] 5 7
## [2,] 6 8
- Create and print a list.
l <- list(TRUE, 1L, 2.34, "abc")
l
## [[1]]
## [1] TRUE
##
## [[2]]
## [1] 1
##
## [[3]]
## [1] 2.34
##
## [[4]]
## [1] "abc"
- Create and print a set of factors.
genders <- c("Male", "Female", "Male", "Male", "Female")
factor <- factor(genders)
factor
## [1] Male Female Male Male Female
## Levels: Female Male
levels(factor)
## [1] "Female" "Male"
unclass(factor)
## [1] 2 1 2 2 1
## attr(,"levels")
## [1] "Female" "Male"
Data Frames
- Create and print a data frame.
df <- data.frame(
Name = c("Cat", "Dog", "Cow", "Pig"),
HowMany = c(5, 10, 15, 20),
IsPet = c(TRUE, TRUE, FALSE, FALSE))
df
## Name HowMany IsPet
## 1 Cat 5 TRUE
## 2 Dog 10 TRUE
## 3 Cow 15 FALSE
## 4 Pig 20 FALSE
- Index the data frame by row and column.
df[1, 2]
## [1] 5
- Index the data frame by row.
df[1, ]
## Name HowMany IsPet
## 1 Cat 5 TRUE
- Index the data frame by column index.
df[ , 2]
## [1] 5 10 15 20
- Index the data frame by column name.
df[["HowMany"]]
## [1] 5 10 15 20
- Index the data frame by column name (shorthand).
df$HowMany
## [1] 5 10 15 20
- Subset using a vector of indexes.
df[c(2, 4), ]
## Name HowMany IsPet
## 2 Dog 10 TRUE
## 4 Pig 20 FALSE
- Subset using a sequence of indexes.
df[2:4, ]
## Name HowMany IsPet
## 2 Dog 10 TRUE
## 3 Cow 15 FALSE
## 4 Pig 20 FALSE
- Subset using a vector of logicals.
df[c(TRUE, FALSE, TRUE, FALSE), ]
## Name HowMany IsPet
## 1 Cat 5 TRUE
## 3 Cow 15 FALSE
- Subset using the equality operator.
df[df$IsPet == TRUE, ]
## Name HowMany IsPet
## 1 Cat 5 TRUE
## 2 Dog 10 TRUE
- Subset using an inequality operator.
df[df$HowMany > 10, ]
## Name HowMany IsPet
## 3 Cow 15 FALSE
## 4 Pig 20 FALSE
- Subset using the match operator.
df[df$Name %in% c("Cat", "Cow"), ]
## Name HowMany IsPet
## 1 Cat 5 TRUE
## 3 Cow 15 FALSE