R - Vectors: A Beginner's Guide

Hello there, future R programmers! Today, we're going to embark on an exciting journey into the world of vectors in R. Don't worry if you've never programmed before – I'll be your friendly guide, and we'll take this step-by-step. By the end of this tutorial, you'll be creating and manipulating vectors like a pro!

R - Vectors

What is a Vector?

Before we dive in, let's understand what a vector is. In R, a vector is like a container that holds multiple items of the same type. Think of it as a train with several carriages, each carrying the same kind of cargo. This cargo could be numbers, text, or even logical values (true/false).

Vector Creation

Let's start by learning how to create vectors. There are several ways to do this in R, but we'll focus on the most common and useful methods.

Using the c() function

The most straightforward way to create a vector is using the c() function. The 'c' stands for 'combine' or 'concatenate'.

# Creating a numeric vector
numbers <- c(1, 2, 3, 4, 5)
print(numbers)

# Creating a character vector
fruits <- c("apple", "banana", "cherry")
print(fruits)

# Creating a logical vector
is_student <- c(TRUE, FALSE, TRUE, TRUE)
print(is_student)

In these examples, we're creating three different types of vectors. The <- symbol is used to assign the vector to a variable name.

Using the : operator

For creating a sequence of numbers, the : operator is super handy:

# Creating a sequence from 1 to 10
sequence <- 1:10
print(sequence)

# Creating a reverse sequence
reverse_sequence <- 10:1
print(reverse_sequence)

This is a quick way to create a sequence of integers. It's like telling R, "Give me all the numbers from this to that."

Using the seq() function

For more control over your sequences, the seq() function is your friend:

# Creating a sequence with a specific step
by_twos <- seq(from = 0, to = 10, by = 2)
print(by_twos)

# Creating a sequence with a specific length
five_numbers <- seq(from = 0, to = 1, length.out = 5)
print(five_numbers)

The seq() function is more flexible, allowing you to specify the start, end, step size, or the number of elements you want.

Using the rep() function

Sometimes, you might want to repeat values. That's where rep() comes in:

# Repeating a single value
repeat_five <- rep(5, times = 3)
print(repeat_five)

# Repeating a vector
repeat_vector <- rep(c(1, 2), times = 3)
print(repeat_vector)

# Repeating each element
repeat_each <- rep(c(1, 2), each = 3)
print(repeat_each)

rep() is great for creating patterns or padding your data with repeated values.

Accessing Vector Elements

Now that we know how to create vectors, let's learn how to access their elements. In R, we use square brackets [] for this purpose.

Accessing by Index

Remember, in R, indexing starts at 1, not 0 like in some other programming languages.

fruits <- c("apple", "banana", "cherry", "date")

# Accessing the first element
print(fruits[1])  # Output: "apple"

# Accessing the third element
print(fruits[3])  # Output: "cherry"

# Accessing multiple elements
print(fruits[c(1, 3)])  # Output: "apple" "cherry"

# Accessing a range of elements
print(fruits[2:4])  # Output: "banana" "cherry" "date"

Negative Indexing

In R, you can use negative indexes to exclude elements:

# Excluding the second element
print(fruits[-2])  # Output: "apple" "cherry" "date"

# Excluding multiple elements
print(fruits[c(-1, -3)])  # Output: "banana" "date"

Logical Indexing

You can also use logical vectors to access elements:

numbers <- c(1, 2, 3, 4, 5)

# Accessing even numbers
print(numbers[numbers %% 2 == 0])  # Output: 2 4

# Accessing numbers greater than 3
print(numbers[numbers > 3])  # Output: 4 5

Vector Manipulation

Now that we can create and access vectors, let's learn how to manipulate them.

Vector Arithmetic

You can perform arithmetic operations on vectors:

vec1 <- c(1, 2, 3)
vec2 <- c(4, 5, 6)

# Addition
print(vec1 + vec2)  # Output: 5 7 9

# Multiplication
print(vec1 * vec2)  # Output: 4 10 18

# Division
print(vec2 / vec1)  # Output: 4 2.5 2

Vector Recycling

When performing operations on vectors of different lengths, R will recycle the shorter vector:

short_vec <- c(1, 2)
long_vec <- c(1, 2, 3, 4, 5, 6)

print(short_vec + long_vec)  # Output: 2 4 4 6 6 8

R repeats the shorter vector to match the length of the longer one.

Vector Functions

R provides many useful functions for working with vectors:

numbers <- c(5, 2, 8, 1, 9)

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

# Sum of all elements
print(sum(numbers))  # Output: 25

# Mean (average) of the vector
print(mean(numbers))  # Output: 5

# Sorting the vector
print(sort(numbers))  # Output: 1 2 5 8 9

Here's a table summarizing some common vector functions:

Function Description
length() Returns the number of elements in the vector
sum() Calculates the sum of all elements
mean() Calculates the average of all elements
median() Finds the median value
max() Returns the maximum value
min() Returns the minimum value
sort() Sorts the vector in ascending order
rev() Reverses the order of elements

Conclusion

Congratulations! You've just taken your first steps into the world of vectors in R. We've covered creation, accessing elements, and basic manipulation. Remember, practice makes perfect, so don't hesitate to experiment with these concepts.

Vectors are the building blocks of data manipulation in R, and mastering them will set you up for success in your R programming journey. Keep exploring, keep coding, and most importantly, have fun with it!

Credits: Image by storyset