Vectors in R

📘 Introduction

A vector is the most fundamental data structure in R. It is a one-dimensional collection of elements of the same data type. Vectors are used to store multiple values in a single object, making data storage, manipulation, and analysis efficient. Almost every operation in R is built around vectors, making them one of the most important concepts to master.

Information

All elements in an R vector must have the same data type. If different data types are combined, R automatically converts them to a common type through type coercion.

đŸŽ¯ Why Use Vectors?

  • Store multiple values in a single object.
  • Perform operations on multiple elements simultaneously.
  • Reduce repetitive code.
  • Support efficient data analysis.
  • Serve as the foundation for many other R data structures.

📝 Creating Vectors

The c() function (combine or concatenate) is the most common way to create vectors in R.

Creating a Numeric Vector

numbers <- c(10, 20, 30, 40, 50)

print(numbers)

Output

Console Output

[1] 10 20 30 40 50

📚 Types of Vectors

Numeric Vector

prices <- c(99.5, 120.75, 250.00)

print(prices)

Integer Vector

ages <- c(18L, 21L, 25L)

print(ages)

Character Vector

cities <- c("Delhi", "Mumbai", "Chennai")

print(cities)

Logical Vector

status <- c(TRUE, FALSE, TRUE)

print(status)

🔄 Type Coercion in Vectors

When different data types are combined, R automatically converts all elements to a common data type.

Type Coercion Example

values <- c(100, TRUE, "R")

print(values)
class(values)

Output

Console Output

[1] "100" "TRUE" "R"
[1] "character"

Important

The presence of a character value causes the entire vector to become a character vector.

📏 Creating Sequences

R provides several ways to generate sequences of numbers.

Using : Operator

numbers <- 1:10

print(numbers)

Using seq()

numbers <- seq(5, 25, by = 5)

print(numbers)

Using rep()

numbers <- rep(3, times = 5)

print(numbers)

đŸŽ¯ Accessing Vector Elements

Vector elements are accessed using square brackets [ ]. R uses 1-based indexing, meaning the first element has index 1.

Accessing Elements

fruits <- c("Apple", "Banana", "Orange", "Mango")

print(fruits[1])
print(fruits[3])

Output

Console Output

[1] "Apple"
[1] "Orange"

âœī¸ Modifying Vector Elements

Updating Elements

marks <- c(75, 82, 90)

marks[2] <- 85

print(marks)

Output

Console Output

[1] 75 85 90

➕ Adding Elements

New elements can be appended using the c() function.

Appending Elements

numbers <- c(10, 20, 30)

numbers <- c(numbers, 40, 50)

print(numbers)

❌ Removing Elements

Elements can be removed by using negative indexing.

Removing Elements

numbers <- c(10, 20, 30, 40, 50)

numbers <- numbers[-3]

print(numbers)

Output

Console Output

[1] 10 20 40 50

🧮 Vector Operations

Arithmetic operations are performed element by element.

Arithmetic Operations

a <- c(10, 20, 30)
b <- c(1, 2, 3)

print(a + b)
print(a - b)
print(a * b)
print(a / b)

Output

Console Output

[1] 11 22 33
[1] 9 18 27
[1] 10 40 90
[1] 10 10 10

📊 Useful Vector Functions

FunctionDescriptionExample
length()Returns the number of elements.length(x)
sum()Calculates the sum.sum(x)
mean()Calculates the average.mean(x)
max()Returns the largest value.max(x)
min()Returns the smallest value.min(x)
sort()Sorts elements.sort(x)

Using Vector Functions

marks <- c(85, 92, 76, 88)

print(length(marks))
print(sum(marks))
print(mean(marks))
print(max(marks))
print(min(marks))
print(sort(marks))

🔍 Vector Comparison

Comparison Operations

marks <- c(60, 75, 90, 45)

print(marks >= 50)

Output

Console Output

[1] TRUE TRUE TRUE FALSE

🔄 Vector Recycling Rule

When vectors of different lengths are used in an operation, R automatically repeats the shorter vector until it matches the length of the longer vector.

Vector Recycling

a <- c(10, 20, 30, 40)
b <- c(2, 4)

print(a + b)

Output

Console Output

[1] 12 24 32 44

Warning

If the length of the longer vector is not a multiple of the shorter vector, R issues a warning because recycling may produce unintended results.

🧭 Vector Workflow

Create a Vector
Store Multiple Values
Access Elements
Modify Elements
Perform Operations
Analyze Results

🌍 Real-World Example

Monthly Sales Analysis

sales <- c(25000, 27000, 30000, 32000, 28000)

print(sales)

print(sum(sales))
print(mean(sales))
print(max(sales))
print(min(sales))

âš ī¸ Common Mistakes

MistakeExplanationSolution
Using index 0R uses 1-based indexing.Begin indexing from 1.
Mixing incompatible data typesAutomatic coercion changes the vector type.Store similar data types together.
Ignoring recycling warningsMay produce unexpected results.Ensure vector lengths are compatible.
Using parentheses instead of bracketsVectors are indexed with square brackets.Use [ ] to access elements.

💡 Best Practices

  • Store only related values in a vector.
  • Use descriptive variable names for vectors.
  • Keep vector elements of the same data type.
  • Use built-in vector functions instead of writing manual calculations.
  • Be mindful of automatic type coercion and vector recycling.

Best Practice

Vectors are optimized for fast, element-wise operations. Whenever possible, use vectorized operations instead of explicit loops for cleaner and more efficient R code.

📝 Summary

Vectors are the fundamental data structure in R, allowing you to store and manipulate multiple values of the same data type efficiently. You learned how to create vectors, access and modify elements, generate sequences, perform vectorized arithmetic, use built-in vector functions, and understand important concepts such as type coercion and the recycling rule. Mastering vectors is essential because they form the basis of many advanced R data structures and data analysis techniques.

>>"Mastering vectors is the first step toward mastering data analysis in R."