Now that objects have been created, it is time to use those same principles to create vectors. Like objects, vectors contain information, just more of it. Before, we had x <- 5, however, what if we wanted x to contain every single letter in the alphabet, and not just one thing (5)?
# Numeric vector
number_vector <- c(1, 2, 3, 4, 5) # c stands for combine/concatenate
number_vector
numeric_vector_2 <- c(6:10) # The colon is like saying "everything from 6 to 10"
numeric_vector_2
# The length command tells you how many values are inside the vector
length(number_vector) # 5
length(numeric_vector_2) # 5
# It is possible to add numeric vectors as long as they're the same length
number_vector + numeric_vector_2
# Vectorized math
number_vector * 10
Just like with numeric data, we can create vectors with characters inside. Unlike with numeric values in R, characters must be in between quotation marks. Notice once quotation marks are used, everything inside (and the quotation marks themselves) change color in your script.
# Quotation marks around each of the fruits
fruits <- c("apple", "banana", "cherry")
fruits
# Quotation marks around the entire string
Fruits <- c("apple, banana, cherry")
Fruits
# Using full word capitalized
some_truths <- c(TRUE, FALSE, TRUE)
some_truths
class(some_truths)
# Using first letter capitalized
some_lies <- c(F, F, T)
some_lies
class(some_lies)
# Once you put quotation marks, it makes them a character
truth_logic <- c("TRUE","FALSE","TRUE")
class(truth_logic)
Above we used the class() command to check to see what type of data we were creating. some_truth and some_lies were both logical, while truth_logic was character.
When character values have levels, it becomes categorical data. In R, this is best handled as factors. To turn a character string into factors, utilize the factor() command.
# Creating the colors vector as factors
colors <- factor(c("red", "blue", "red", "green")) # 4 values
colors
class(colors)
levels(colors) # Checking to see how many levels there are (3)
[1] red blue red green
Levels: blue green red
[1] "factor"
[1] "blue" "green" "red"
When we called class() we saw that colors was factor, not character. In order to check to see how many levels were inside colors, we used the levels() command, which indicated that there were three: blue, green, and red.
Vectors, unlike objects, have multiple values inside of them. For instance, when we created the vector fruits, it had three values: apple, banana, cherry. Vectors inherently are indexed meaning that there is positioning inside of the vector. For fruits, apple would be 1, banana would be 2, and cherry would be 3. In R, we can utilize this indexing to our advantage and call specific positions from vectors. To do this, we will be using brackets.
In the previous sections, we created vectors, but theyβve all been the same data type. What about if we put some different types of data, for instance, numeric and character, into a vector?