R Vectors Tutorial with Examples

In R, a vector is the most basic data structure and is essential for data analysis and manipulation. A vector is a sequence of elements of the same data type, such as numbers, characters, or logical values.

Vectors can be one-dimensional arrays, and they are widely used for performing operations on data efficiently.

In this tutorial, we will cover:

Let’s dive into each of these topics with examples!

1. What is a Vector in R?

A vector is a one-dimensional array that can contain elements of the same type, such as numeric, character, or logical values. Vectors are fundamental in R programming, and many functions operate on vectors.

Example of Different Types of Vectors:

# Numeric vector
numeric_vec <- c(1, 2, 3, 4)

# Character vector
char_vec <- c("apple", "banana", "cherry")

# Logical vector
logical_vec <- c(TRUE, FALSE, TRUE)

print(numeric_vec)  # Outputs: 1 2 3 4
print(char_vec)     # Outputs: "apple" "banana" "cherry"
print(logical_vec)  # Outputs: TRUE FALSE TRUE
  • Each vector contains elements of the same data type.

2. Creating Vectors

Vectors can be created using the c() function, which stands for “combine” or “concatenate”. You can also use functions like : and seq() to create numeric sequences.

Example (Using c() to Create a Vector):

# Create a numeric vector
num_vector <- c(10, 20, 30, 40)
print(num_vector)  # Outputs: 10 20 30 40

# Create a character vector
char_vector <- c("A", "B", "C")
print(char_vector)  # Outputs: "A" "B" "C"

Example (Creating a Sequence Vector with :):

# Create a sequence of numbers from 1 to 5
seq_vector <- 1:5
print(seq_vector)  # Outputs: 1 2 3 4 5
  • The : operator creates a sequence of numbers.

3. Accessing Vector Elements

You can access individual elements in a vector using square brackets [ ] and specifying the index of the element. Indexing in R starts from 1.

Example:

# Access elements in a vector
vec <- c(5, 10, 15, 20)

# Access the first element
first_element <- vec[1]
print(first_element)  # Outputs: 5

# Access the third element
third_element <- vec[3]
print(third_element)  # Outputs: 15

# Access multiple elements
subset <- vec[c(1, 3, 4)]
print(subset)  # Outputs: 5 15 20
  • You can specify a single index to access one element or multiple indices to access multiple elements.

4. Modifying Vector Elements

You can modify elements of a vector by assigning new values to specific indices.

Example:

# Modify elements in a vector
vec <- c(5, 10, 15, 20)

# Modify the second element
vec[2] <- 100
print(vec)  # Outputs: 5 100 15 20

# Modify multiple elements
vec[c(1, 3)] <- c(50, 150)
print(vec)  # Outputs: 50 100 150 20
  • You can assign new values to specific elements or multiple elements simultaneously.

5. Basic Operations on Vectors

R allows you to perform element-wise operations on vectors. You can add, subtract, multiply, and divide vectors of the same length.

Example:

# Create two numeric vectors
vec1 <- c(1, 2, 3)
vec2 <- c(4, 5, 6)

# Perform element-wise operations
sum_vec <- vec1 + vec2  # Addition
diff_vec <- vec1 - vec2  # Subtraction
prod_vec <- vec1 * vec2  # Multiplication
div_vec <- vec1 / vec2   # Division

print(sum_vec)   # Outputs: 5 7 9
print(diff_vec)  # Outputs: -3 -3 -3
print(prod_vec)  # Outputs: 4 10 18
print(div_vec)   # Outputs: 0.25 0.40 0.50
  • The operations are applied element-wise to vectors of the same length.

6. Vector Functions (length(), sort(), rev(), etc.)

R provides several functions to manipulate and analyze vectors.

Example (Getting the Length of a Vector):

# Get the length of a vector
vec <- c(10, 20, 30, 40)
len <- length(vec)
print(len)  # Outputs: 4

Example (Sorting a Vector):

# Sort a vector
unsorted_vec <- c(30, 10, 20, 50)
sorted_vec <- sort(unsorted_vec)
print(sorted_vec)  # Outputs: 10 20 30 50

Example (Reversing a Vector):

# Reverse a vector
reversed_vec <- rev(unsorted_vec)
print(reversed_vec)  # Outputs: 50 20 10 30
  • The length(), sort(), and rev() functions are commonly used to manipulate vectors.

7. Combining Vectors

You can combine two or more vectors into a single vector using the c() function.

Example:

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

combined_vec <- c(vec1, vec2)
print(combined_vec)  # Outputs: 1 2 3 4 5 6
  • The c() function combines the elements of both vectors into a new vector.

8. Sequence Vectors (: and seq())

The : operator and seq() function are used to create sequences of numbers in R.

Example (Using :):

# Create a sequence from 1 to 10
seq_vec <- 1:10
print(seq_vec)  # Outputs: 1 2 3 4 5 6 7 8 9 10

Example (Using seq()):

# Create a sequence with custom step size
seq_vec <- seq(1, 10, by = 2)
print(seq_vec)  # Outputs: 1 3 5 7 9
  • The seq() function allows you to specify the start, end, and step size.

9. Repeating Vectors (rep())

The rep() function is used to repeat elements of a vector.

Example (Repeating Elements):

# Repeat the elements of a vector
vec <- c(1, 2, 3)

# Repeat each element 3 times
rep_vec <- rep(vec, times = 3)
print(rep_vec)  # Outputs: 1 2 3 1 2 3 1 2 3

# Repeat each element with a specified number of times
rep_each_vec <- rep(vec, each = 3)
print(rep_each_vec)  # Outputs: 1 1 1 2 2 2 3 3 3
  • The rep() function is used to repeat either the whole vector or individual elements.

10. Logical Vectors

A logical vector contains boolean values (TRUE or FALSE). Logical vectors are often used in conditional operations and indexing.

Example (Logical Operations):

# Create a logical vector
vec <- c(10, 20, 30, 40)

# Check if elements are greater than 25
logic_vec <- vec > 25
print(logic_vec)  # Outputs: FALSE FALSE TRUE TRUE

Example (Using Logical Vectors for Subsetting):

# Subset the vector based on a condition
subset_vec <- vec[vec > 25]
print(subset_vec)  # Outputs: 30 40
  • Logical vectors are often used to filter data based on conditions.

Summary of Common Vector Functions in R

Function Description
c() Creates a vector by combining elements.
: Creates a sequence of numbers.
length() Returns the length of a vector.
sort() Sorts a vector.
rev() Reverses a vector.
seq() Generates a sequence with custom start, end, and step.
rep() Repeats elements in a vector.
[ ] Accesses or modifies elements in a vector.

Conclusion

Vectors are one of the most fundamental data structures in R, and understanding how to create, access, modify, and perform operations on vectors is crucial for efficient data manipulation.

This tutorial covered:

  • Creating vectors using the c() function, :, and seq().
  • Accessing and modifying vector elements.
  • Performing basic arithmetic operations on vectors.
  • Using built-in functions like length(), sort(), and rev() to manipulate vectors.
  • Creating sequence vectors with : and seq(), and repeating vectors with rep().

By mastering these vector operations, you’ll have a solid foundation for working with data in R.

 

Related posts

R Factors Tutorial with Examples

R Matrices Tutorial with Examples

R Arrays Tutorial with Examples