Vectors in R

Topic: Vectors

Advertisement

Introduction

Vectors are the most fundamental data structure in R. A vector is a collection of elements of the same type.

Creating Vectors

# Using c() function
numbers <- c(1, 2, 3, 4, 5)
letters <- c("a", "b", "c", "d")
logical_vec <- c(TRUE, FALSE, TRUE)

# Using colon operator
1:10

# Using seq() function
seq(1, 10, by = 2)
seq(0, 1, length.out = 5)

# Using rep() function
rep(1, times = 5)
rep(c(1, 2), each = 3)

Vector Operations

# Arithmetic operations
v1 <- c(1, 2, 3)
v2 <- c(4, 5, 6)

v1 + v2      # Element-wise addition
v1 - v2      # Element-wise subtraction
v1 * v2      # Element-wise multiplication
v1 / v2      # Element-wise division

# Scalar operations
v1 + 10      # Add 10 to each element
v1 * 2       # Multiply each element by 2

Vector Functions

v <- c(3, 1, 4, 1, 5, 9, 2, 6)

length(v)    # Number of elements
sum(v)       # Sum of elements
prod(v)      # Product of elements
mean(v)      # Mean
median(v)    # Median
sd(v)        # Standard deviation
min(v)       # Minimum
max(v)       # Maximum
range(v)     # Range
sort(v)      # Sort ascending
sort(v, decreasing = TRUE)  # Sort descending

Indexing Vectors

v <- c("a", "b", "c", "d", "e")

# By position
v[1]         # First element
v[c(1, 3)]   # Multiple positions
v[1:3]       # Range of positions
v[-1]        # All except first
v[-c(1, 2)]  # Exclude first two

# By condition
v[v > 3]
v[v == "a"]

Vector Properties

v <- c(1, 2, 3)

is.vector(v)     # Check if vector
is.numeric(v)    # Check if numeric
is.character(v)  # Check if character
is.logical(v)    # Check if logical

Summary

Vectors are the building blocks of R. Master vector operations to become proficient in R programming.

Advertisement

Advertisement

Need More Practice?

Get personalized R programming help from ChatWhole's AI-powered platform.

Get Expert Help →