Vectors in R Programming

Vectors in R Programming | Tutorial and Examples

Vectors in R – Study Material

Vectors in R – Complete Study Guide

Topic 1: Vectors in R

In R, a vector is the most basic data structure that contains elements of the same data type. Think of a vector as a sequence of data elements that are organized in a one-dimensional array. Vectors can hold numeric values, character strings, or logical values, but all elements in a single vector must be of the same type.

Vectors are fundamental to R programming because most operations in R are vectorized, meaning they automatically apply to each element of a vector without the need for explicit loops. This makes R code more concise and efficient.

Example: A numeric vector containing the ages of five people:

# Creating a numeric vector
ages <- c(25, 32, 41, 19, 55)
print(ages)
# Output: [1] 25 32 41 19 55

Vectors can be of different types:

  • Numeric vectors: Contain numbers (e.g., c(1, 2, 3, 4))
  • Character vectors: Contain text (e.g., c(“apple”, “banana”, “cherry”))
  • Logical vectors: Contain TRUE/FALSE values (e.g., c(TRUE, FALSE, TRUE))

Understanding vectors is crucial because they form the building blocks for more complex data structures like matrices and data frames in R.

Practice Exercise

1. Create a numeric vector containing the first five prime numbers: 2, 3, 5, 7, 11.

2. Create a character vector with the names of three fruits.

3. Create a logical vector with three elements: TRUE, FALSE, TRUE.

Answer and Solutions

# Solution to Exercise 1
primes <- c(2, 3, 5, 7, 11)
print(primes)

# Solution to Exercise 2
fruits <- c(“apple”, “banana”, “orange”)
print(fruits)

# Solution to Exercise 3
logical_vec <- c(TRUE, FALSE, TRUE)
print(logical_vec)

Topic 2: Creating Vectors Using Different Methods

R provides several methods to create vectors, each useful in different scenarios. The most common method is using the c() function, which combines values into a vector. However, there are other efficient methods for specific use cases.

1. Using the c() function: This is the most straightforward method to create vectors by combining elements.

# Creating vectors with c()
numbers <- c(10, 20, 30, 40)
colors <- c(“red”, “green”, “blue”)

2. Using the colon operator (:): This creates a sequence of numbers with increments of 1.

# Creating a sequence from 1 to 5
sequence1 <- 1:5
print(sequence1) # Output: [1] 1 2 3 4 5

# Creating a sequence from 10 to 15
sequence2 <- 10:15
print(sequence2) # Output: [1] 10 11 12 13 14 15

3. Using the seq() function: This function provides more control over sequences, allowing you to specify start, end, and step size.

# Creating a sequence from 1 to 10 with step 2
even_numbers <- seq(1, 10, by = 2)
print(even_numbers) # Output: [1] 1 3 5 7 9

# Creating a sequence of length 5 between 0 and 1
fractions <- seq(0, 1, length.out = 5)
print(fractions) # Output: [1] 0.00 0.25 0.50 0.75 1.00

4. Using the rep() function: This function repeats values a specified number of times.

# Repeating a value 5 times
repeated <- rep(7, times = 5)
print(repeated) # Output: [1] 7 7 7 7 7

# Repeating a vector
repeated_vec <- rep(c(1, 2), times = 3)
print(repeated_vec) # Output: [1] 1 2 1 2 1 2

Practice Exercise

1. Create a vector containing the numbers from 5 to 15 using the colon operator.

2. Create a sequence from 0 to 1 with 6 equally spaced values using the seq() function.

3. Create a vector that repeats the pattern “A”, “B”, “C” three times using the rep() function.

Answer and Solutions

# Solution to Exercise 1
vec1 <- 5:15
print(vec1)

# Solution to Exercise 2
vec2 <- seq(0, 1, length.out = 6)
print(vec2)

# Solution to Exercise 3
vec3 <- rep(c(“A”, “B”, “C”), times = 3)
print(vec3)

Topic 3: Performing Operations on Vectors

One of R’s powerful features is vectorization, which allows operations to be applied to entire vectors without explicit looping. When you perform an operation on a vector, R applies it to each element automatically.

Arithmetic Operations: Basic arithmetic operations work element-wise on vectors.

# Creating two vectors
vec1 <- c(1, 2, 3, 4)
vec2 <- c(5, 6, 7, 8)

# Addition
sum_vec <- vec1 + vec2
print(sum_vec) # Output: [1] 6 8 10 12

# Multiplication
product_vec <- vec1 * vec2
print(product_vec) # Output: [1] 5 12 21 32

# Exponentiation
power_vec <- vec1 ^ 2
print(power_vec) # Output: [1] 1 4 9 16

Recycling: When vectors of different lengths are used in operations, R recycles the shorter vector to match the length of the longer one.

# Vector recycling example
long_vec <- 1:6
short_vec <- c(10, 20)

# R recycles short_vec to match the length of long_vec
result <- long_vec + short_vec
print(result) # Output: [1] 11 22 13 24 15 26
# Explanation: 1+10=11, 2+20=22, 3+10=13, 4+20=24, etc.

Comparison Operations: You can compare vectors element-wise, resulting in a logical vector.

# Comparison operations
vec <- c(10, 20, 30, 40)

# Check which elements are greater than 25
greater_than_25 <- vec > 25
print(greater_than_25) # Output: [1] FALSE FALSE TRUE TRUE

# Check which elements are equal to 20
equal_to_20 <- vec == 20
print(equal_to_20) # Output: [1] FALSE TRUE FALSE FALSE

Vector Functions: R provides many functions that work on vectors.

# Common vector functions
numbers <- c(3, 7, 2, 9, 5)

# Length of vector
length(numbers) # Output: 5

# Sum of elements
sum(numbers) # Output: 26

# Mean of elements
mean(numbers) # Output: 5.2

# Sort the vector
sort(numbers) # Output: [1] 2 3 5 7 9

Practice Exercise

1. Create two vectors: a = c(2, 4, 6) and b = c(1, 3, 5). Calculate a + b and a * b.

2. Given x = c(10, 20, 30, 40) and y = c(2, 4), calculate x / y (observe recycling).

3. For vector z = c(15, 25, 35, 45), find which elements are greater than 30.

Answer and Solutions

# Solution to Exercise 1
a <- c(2, 4, 6)
b <- c(1, 3, 5)
sum_ab <- a + b
product_ab <- a * b
print(sum_ab) # Output: [1] 3 7 11
print(product_ab) # Output: [1] 2 12 30

# Solution to Exercise 2
x <- c(10, 20, 30, 40)
y <- c(2, 4)
division <- x / y
print(division) # Output: [1] 5 5 15 10
# Explanation: 10/2=5, 20/4=5, 30/2=15, 40/4=10

# Solution to Exercise 3
z <- c(15, 25, 35, 45)
greater_than_30 <- z > 30
print(greater_than_30) # Output: [1] FALSE FALSE TRUE TRUE

Topic 4: Indexing and Subsetting Vectors Effectively

Indexing allows you to access specific elements or subsets of a vector. In R, indexing starts at 1 (unlike some other programming languages that start at 0). You can use positive integers, negative integers, logical values, or names to subset vectors.

Positive Integer Indexing: Extract elements at specific positions.

# Creating a vector
fruits <- c(“apple”, “banana”, “cherry”, “date”, “elderberry”)

# Access the first element
first_fruit <- fruits[1]
print(first_fruit) # Output: “apple”

# Access multiple elements
selected_fruits <- fruits[c(1, 3, 5)]
print(selected_fruits) # Output: “apple” “cherry” “elderberry”

Negative Integer Indexing: Exclude elements at specific positions.

# Exclude the second element
without_banana <- fruits[-2]
print(without_banana) # Output: “apple” “cherry” “date” “elderberry”

# Exclude multiple elements
without_several <- fruits[c(-2, -4)]
print(without_several) # Output: “apple” “cherry” “elderberry”

Logical Indexing: Extract elements based on a condition.

# Creating a numeric vector
numbers <- c(10, 25, 30, 45, 50)

# Extract elements greater than 30
large_numbers <- numbers[numbers > 30]
print(large_numbers) # Output: [1] 45 50

# Extract even numbers
even_numbers <- numbers[numbers %% 2 == 0]
print(even_numbers) # Output: [1] 10 30 50

Using which() function: The which() function returns the indices of elements that satisfy a condition.

# Find indices of elements greater than 30
indices <- which(numbers > 30)
print(indices) # Output: [1] 4 5

# Use these indices to subset the vector
selected <- numbers[indices]
print(selected) # Output: [1] 45 50

Practice Exercise

1. Given v = c(5, 10, 15, 20, 25, 30), extract the first, third, and fifth elements.

2. From the same vector, exclude the second and fourth elements.

3. Extract all elements greater than 15 using logical indexing.

Answer and Solutions

# Solution to Exercise 1
v <- c(5, 10, 15, 20, 25, 30)
selected1 <- v[c(1, 3, 5)]
print(selected1) # Output: [1] 5 15 25

# Solution to Exercise 2
selected2 <- v[c(-2, -4)]
print(selected2) # Output: [1] 5 15 25 30

# Solution to Exercise 3
selected3 <- v[v > 15]
print(selected3) # Output: [1] 20 25 30

Topic 5: Working with Named Vectors

Named vectors are vectors where each element has a name associated with it. This makes your code more readable and allows you to access elements by name instead of position. Names can be added when creating the vector or assigned later using the names() function.

Creating Named Vectors: You can create named vectors in several ways.

# Method 1: Using the c() function with names
temperatures <- c(Monday = 72, Tuesday = 68, Wednesday = 75, Thursday = 70, Friday = 78)
print(temperatures)
# Output: Monday Tuesday Wednesday Thursday Friday
# 72 68 75 70 78

# Method 2: Assigning names after creating the vector
scores <- c(95, 87, 92)
names(scores) <- c(“Math”, “Science”, “History”)
print(scores)
# Output: Math Science History
# 95 87 92

Accessing Elements by Name: You can use names instead of indices to access elements.

# Accessing elements by name
monday_temp <- temperatures[“Monday”]
print(monday_temp) # Output: Monday 72

# Accessing multiple elements by name
weekdays_temp <- temperatures[c(“Monday”, “Wednesday”, “Friday”)]
print(weekdays_temp)
# Output: Monday Wednesday Friday
# 72 75 78

Modifying Names: You can change the names of vector elements.

# Changing names
names(temperatures)[1] <- “Mon”
names(temperatures)[3] <- “Wed”
print(temperatures)
# Output: Mon Tuesday Wed Thursday Friday
# 72 68 75 70 78

# Removing names
unnamed_temps <- unname(temperatures)
print(unnamed_temps) # Output: [1] 72 68 75 70 78

Benefits of Named Vectors:

  • Code becomes more self-documenting and readable
  • You don’t need to remember positions of elements
  • Makes data manipulation more intuitive
  • Useful when working with functions that return named vectors

Practice Exercise

1. Create a named vector called “prices” with elements: Apple = 1.2, Banana = 0.8, Orange = 1.5.

2. Extract the price of Banana using its name.

3. Change the name “Orange” to “Citrus” in the prices vector.

Answer and Solutions

# Solution to Exercise 1
prices <- c(Apple = 1.2, Banana = 0.8, Orange = 1.5)
print(prices)

# Solution to Exercise 2
banana_price <- prices[“Banana”]
print(banana_price)

# Solution to Exercise 3
names(prices)[names(prices) == “Orange”] <- “Citrus”
print(prices)

Important Note

Remember that all elements in a vector must be of the same data type. If you try to mix types, R will convert them to a common type following a specific hierarchy: logical → integer → numeric → character.

Educational Resources Footer