A vector is the most basic data structure in R. It is a sequence of elements that are all of the same type. Vectors can store numeric values, characters, logical values, or other types, but all elements in a single vector must be of the same type.
Use the c()
function to combine values into a vector.
# Numeric vector numbers <- c(10, 20, 30, 40, 50) # Character vector fruits <- c("apple", "banana", "cherry") # Logical vector flags <- c(TRUE, FALSE, TRUE, TRUE)
Use square brackets []
with the index (starting at 1) to access elements.
fruits[2] # "banana" numbers[c(1, 3)] # selects 1st and 3rd elements: 10 and 30 flags[flags == TRUE] # elements where value is TRUE
Vectors support arithmetic and logical operations element-wise.
a <- c(2, 4, 6) b <- c(1, 3, 5) a + b # adds elements: c(3, 7, 11) a * 2 # multiplies each element by 2: c(4, 8, 12) a > 3 # logical comparison: c(FALSE, TRUE, TRUE)
length(x)
– returns number of elementssum(x)
– sums numeric elementsmean(x)
– calculates averagesort(x)
– sorts elementsunique(x)
– returns unique elementsc()
to create vectors.[]
.length()
, sum()
, and mean()
help analyze vectors.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!