Vectors and Lists

Vectors

# Create a vector
v <- c(1, 2, 3, 4, 5, 6)
v
class(v)
# Let's create another vector of the same length
v2 <- c(2, 2, 2, 2, 2, 2)
# Since the data type is numeric, we can do arithmetic here
v3 <- v + v2
v4 <- v * v2

# Can also be a character string
v5 <- c("a", "b", "c")
class(v5)
v6 <- c("1", "2", "3")
v7 <- paste0(v5, v6)
v8 <- c(v5, v6, v7)

# Accessing the elements of a vector
v5[1] 
v5[c(1, 3)]
# Change the element of a vector
v5[1] <- "new element"

Lists

# Create a list 
l <- list(1, 2, 3, 4, 5, 6)
class(l) 

l2 <- list(c(5, 10, 15), "Eric", "McGregor", 1:20, seq(0, 50, 5))

# You can even have a list with lists inside
l2 <- list(c(5, 10, 15), "Eric", "McGregor", 1:20, list(seq(0, 50, 5), seq(0, 100, 20)))

# Accessing the elements of a list
l2[[1]]
l2[[3]]
# To access the list inside the list
l2[[5]][[2]]

# We can also name elements in a list
l3 <- list(first = "Eric", last = "McGregor", music = "funk")
l3$first
l3[["music"]]
# Change a list element
l3[["music"]] <- list(l3[["music"]], "jazz")
l3$music
l3[["music"]] <- "jazz"