Week 2: Working with R's Basic Data
Learn about variables, data types, vectors, and operators in R.
Dive into Chapter 2Introduction to Vectors.
Vectors are arguably the most fundamental data structure in R. They are ordered collections of elements of the same basic data type. Even single values like `x <- 5` are actually vectors of length one.
Creating Vectors
The most common way to create a vector is using the combine function `c()`.
# Numeric vector
numeric_vec <- c(1.5, 2.3, 0.7, 4.1)
# Integer vector
integer_vec <- c(1L, 5L, 10L, 15L)
# Logical vector
logical_vec <- c(TRUE, FALSE, T, F)
# Character vector
character_vec <- c("apple", "banana", "cherry")
# Printing vectors
numeric_vec
character_vec
Vector Coercion
If you try to combine different data types in a single vector using `c()`, R will coerce the elements to the least restrictive type to ensure all elements are the same type. The coercion hierarchy generally goes: Logical -> Integer -> Numeric -> Character.
mixed_vec <- c(1L, "apple", 3.5, TRUE)
mixed_vec # Output: [1] "1" "apple" "3.5" "TRUE"
class(mixed_vec) # Output: [1] "character" (All elements coerced to character)
We will explore vector indexing, slicing, and operations in more detail next week.