Lab 1A: R Language Basics (Easy)

Data Types

  1. Creating and print a logical.
l <- TRUE
l
## [1] TRUE
  1. Create and print an integer.
i <- 123L
i
## [1] 123
  1. Create and print a numeric.
n <- 1.23
n
## [1] 1.23
  1. Create and print a character string.
c <- "ABC 123"
c
## [1] "ABC 123"
  1. Create and invoke a function.
f <- function(x) { x + 1 }
f(2)
## [1] 3

Data Structures

  1. Create and print a vector.
v <- c(1, 2, 3);
v
## [1] 1 2 3
  1. Create and print a sequence.
s <- 1:5
s
## [1] 1 2 3 4 5
  1. 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
  1. 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
  1. 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"
  1. 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

  1. 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
  1. Index the data frame by row and column.
df[1, 2]
## [1] 5
  1. Index the data frame by row.
df[1, ]
##   Name HowMany IsPet
## 1  Cat       5  TRUE
  1. Index the data frame by column index.
df[ , 2]
## [1]  5 10 15 20
  1. Index the data frame by column name.
df[["HowMany"]]
## [1]  5 10 15 20
  1. Index the data frame by column name (shorthand).
df$HowMany
## [1]  5 10 15 20
  1. Subset using a vector of indexes.
df[c(2, 4), ]
##   Name HowMany IsPet
## 2  Dog      10  TRUE
## 4  Pig      20 FALSE
  1. Subset using a sequence of indexes.
df[2:4, ]
##   Name HowMany IsPet
## 2  Dog      10  TRUE
## 3  Cow      15 FALSE
## 4  Pig      20 FALSE
  1. Subset using a vector of logicals.
df[c(TRUE, FALSE, TRUE, FALSE), ]
##   Name HowMany IsPet
## 1  Cat       5  TRUE
## 3  Cow      15 FALSE
  1. Subset using the equality operator.
df[df$IsPet == TRUE, ]
##   Name HowMany IsPet
## 1  Cat       5  TRUE
## 2  Dog      10  TRUE
  1. Subset using an inequality operator.
df[df$HowMany > 10, ]
##   Name HowMany IsPet
## 3  Cow      15 FALSE
## 4  Pig      20 FALSE
  1. Subset using the match operator.
df[df$Name %in% c("Cat", "Cow"), ]
##   Name HowMany IsPet
## 1  Cat       5  TRUE
## 3  Cow      15 FALSE