How to Create a Vector in R
Learn different ways to create vectors in R, the fundamental data structure for storing sequences of values.
Vectors are the most basic data structure in R. Here’s how to create them.
Method 1: Using c() Function
The most common way to create vectors:
# Numeric vector
numbers <- c(1, 2, 3, 4, 5)
print(numbers) # 1 2 3 4 5
# Character vector
names <- c("Alice", "Bob", "Charlie")
print(names)
# Logical vector
flags <- c(TRUE, FALSE, TRUE)
print(flags)
Method 2: Using Colon Operator
Create sequences of integers:
# 1 to 10
nums <- 1:10
print(nums) # 1 2 3 4 5 6 7 8 9 10
# 5 to 1 (descending)
desc <- 5:1
print(desc) # 5 4 3 2 1
Method 3: Using seq() Function
Create sequences with more control:
# Specify start, end, and increment
by_two <- seq(0, 10, by = 2)
print(by_two) # 0 2 4 6 8 10
# Specify length
five_nums <- seq(0, 1, length.out = 5)
print(five_nums) # 0.00 0.25 0.50 0.75 1.00
Method 4: Using rep() Function
Create vectors with repeated values:
# Repeat a value
zeros <- rep(0, 5)
print(zeros) # 0 0 0 0 0
# Repeat a vector
pattern <- rep(c(1, 2), 3)
print(pattern) # 1 2 1 2 1 2
# Repeat each element
each <- rep(c(1, 2, 3), each = 2)
print(each) # 1 1 2 2 3 3
Method 5: Using vector() Function
Create an empty vector of a specific type:
# Numeric vector of length 5
nums <- vector("numeric", 5)
print(nums) # 0 0 0 0 0
# Character vector
chars <- vector("character", 3)
print(chars) # "" "" ""
# Logical vector
flags <- vector("logical", 4)
print(flags) # FALSE FALSE FALSE FALSE
Combining Vectors
v1 <- c(1, 2, 3)
v2 <- c(4, 5, 6)
# Concatenate
combined <- c(v1, v2)
print(combined) # 1 2 3 4 5 6
Named Vectors
Create vectors with named elements:
ages <- c(Alice = 25, Bob = 30, Charlie = 35)
print(ages)
print(ages["Alice"]) # 25
# Or add names later
scores <- c(85, 90, 78)
names(scores) <- c("Math", "Science", "English")
print(scores)
Checking Vector Properties
nums <- c(1, 2, 3, 4, 5)
length(nums) # 5
typeof(nums) # "double"
is.vector(nums) # TRUE
Summary
- Use
c()for creating vectors from values - Use
:orseq()for numeric sequences - Use
rep()for repeated values - Use
vector()for empty vectors of specific length - Use
names()to add or access element names