Vectors

Vectors#

If we want to create a variable that contains multiple pieces of data, we must make a declaration when we assign data to the variable.

# Creating a vector
x <- c(1, 2, 3)
x

# Lazy sequences
x <- 1:3
x

# Creating a vector with variables
x <- 1
y <- 2
z <- c(x, y, 3)
z

Exercise 0.2

  • Create a vector containing the numbers 1 to 10

# create a vector
x <- 1:10
  • What happens if you add 1 to this variable?

# Do some arithmetic
x + 1
# It adds 1 to each value in the vector
  • What happens if you multiple the variable by 2?

x*2
# It multiplies every value by 2
  • What happens if you add the variable to itself?

x + x
# This time it adds the first value to the first value, the second to the second, etc.
  • Now create two vectors of the same length containing different numbers, say 1 to 3 and 4 to 6.

# Create two different vectors
a <- 1:3
b <- 4:6
  • What happens when you add or multiply these together?

# Do some arithmetic
a + b
# It adds them element-wise, i.e.: first to first, etc.
a * b
# It multiplies element-wise
  • What happens if you add or multiply two vectors of different lengths?

# Different length vectors
a + x
# We get a warning, but it produces a result: repeating the shorter vector to have enough elements to add to the larger vector
# But let's try another
x <- 1:6
a + x
# No warning this time because the length of a (3) is a multiple of the length of x (6)
# R assumes you meant to do this, and repeats a twice to add to x