Data Structure: Vector
A list common functions in R for working with vector objects:
1. Creating Vectors
c()
– Combine values into a vector.seq()
– Generate a sequence of numbers.rep()
– Repeat elements to form a vector.
2. Accessing and Modifying Vectors
length()
– Get the length of a vector.[]
– Subset elements of a vector.append()
– Append elements to a vector.unique()
– Extract unique elements from a vector.sort()
– Sort elements of a vector.rev()
– Reverse elements of a vector.which()
– Find indices of elements that meet a condition.
3. Vector Math and Operations
sum()
– Sum of vector elements.mean()
– Calculate the mean.median()
– Calculate the median.sd()
– Calculate the standard deviation.var()
– Calculate the variance.min()
/max()
– Find the minimum/maximum value.range()
– Get the range (min and max).diff()
– Lagged differences of vector elements.prod()
– Product of elements.
4. Logical and Conditional Functions
any()
– Check if any elements areTRUE
.all()
– Check if all elements areTRUE
.is.na()
– Check forNA
values in the vector.na.omit()
– RemoveNA
values from the vector.ifelse()
– Vectorized conditional statements.
5. Applying Functions to Vectors
sapply()
– Apply a function to each element and simplify the result.vapply()
– Similar tosapply()
but allows specifying output type.
6. Character Vector Functions
paste()
/paste0()
– Concatenate elements.tolower()
/toupper()
– Convert to lowercase or uppercase.nchar()
– Count characters in elements.substr()
– Extract or replace substrings.
7. Set Operations
union()
– Union of two vectors.intersect()
– Intersection of two vectors.setdiff()
– Elements in one vector but not the other.%in%
– Check if elements are in another vector.
8. Other Useful Functions
sample()
– Randomly sample elements from a vector.match()
– Find positions of first matches in a vector.table()
– Frequency table of vector elements.cut()
– Divide a continuous vector into intervals.