Vectors
Assignment Operator, ' <- '
'<-' is used as the assignment operator in R. The assignment operator assigns the value on the right of the operator to the variable on the left of the operator.
For instance, "x <- 1" assigns the number 1 to the variable x. When you create a variable, the console will not return anything, even if it worked:
However, you will see in the Environment pane of RStudio (usually the top right), that a variable has appeared.
If you are only using R (not RStudio) or if you want to simply recall the value of your variable, just type the name of the variable and run the code and R will output that variable's value.
# no pec
x <- 1
However, you will see in the Environment pane of RStudio (usually the top right), that a variable has appeared.
x <- 1
# The value 1 is stored in x.
x
c() function, seq() function, and ' : ' notation
- c() function
If you want to store more than one piece of information into a variable, you can create a vector. The simplest way to create a vector of information is to use the combine function, c().# no pec# This is a vector that contains the numbers specified. vector_num <- c(3, 5, 2, 1, 6, 6, 7) vector_num # This is a vector that contains characters. vector_char <- c("Bill", "Sally", "Ted", "Hannah") vector_char - ' : ' notation and seq() function
vector_1 is a vector of five numbers, 1 through 5. It can be created using the c() function or with a ' : '.
# no pec# Using c() vector_1 <- c(1, 2, 3, 4, 5) vector_1 # Using : vector_2 <- 1:5 vector_2
The sequence function, seq(), can also be useful to create a more specific sequence of numbers.
# no pecvector_3 <- seq(from = 1, to = 5, by = 1) vector_3 even_vector <- seq(from = 0, to = 12, by = 2) even_vectorLogical Operators with Vectors
Logical operators can also be applied to vectors.
Logical operators also work for character vectors.# no pecvector_4 <- c(1, 3, 6, 4, 3, 7, 2) vector_4 > 4
Notice that the logical operator is evaluated for every element in the vector.# no pecvector_5 <- c("Ben", "Jim", "Sally", "sally", "Julie") vector_5 == "Sally"
Notice that R is case sensitive. "Sally" is different from "sally" in R.'[ ]' notation
If you only want a subset of the data that is stored in a vector, you can use bracket notation, '[ ]'.
For example, if we wanted the third element in vector_6 (the number 6), we would type the name of the vector in question followed by a '3' in brackets.You can subset more than one element as well using a variety of methods.
# no pecvector_6 <- c(2, 4, 6, 8, 10) vector_6[3]vector_6 <- c(2, 4, 6, 8, 10)# This will subset the vector to only include the 2nd, 3rd, and 4th elements. vector_6[2:4] # This will subset the vector to only include the 1st, 2nd, and 5th elements. vector_6[c(1, 2, 5)] # This will subset the vector to only include elements that are greater than 4. vector_6[vector_6 > 4]Video Tutorial: