R
Beginner
1 min read
Vector Utility Functions and String Vectors
Example
# Numeric utilities
v <- c(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5)
mean(v) # 3.818...
median(v) # 4
sd(v) # 2.228...
var(v) # 4.963...
range(v) # 1 9
quantile(v, 0.75) # 5 (75th percentile)
cumsum(v) # running total
diff(v) # lag-1 differences
# Sorting and ordering
sort(v) # ascending
sort(v, decreasing = TRUE) # descending
order(v) # indices that sort v ascending
v[order(v)] # same as sort(v)
# which() — find matching indices
which(v > 4) # positions where v > 4
which.min(v) # position of minimum
which.max(v) # position of maximum
# Set-like operations on vectors
a <- c(1, 2, 3, 4, 5)
b <- c(3, 4, 5, 6, 7)
union(a, b) # 1 2 3 4 5 6 7
intersect(a, b) # 3 4 5
setdiff(a, b) # 1 2 (in a but not b)
4 %in% a # TRUE
# String vectors
fruits <- c("Apple", "banana", "Cherry")
nchar(fruits) # 5 6 6
tolower(fruits) # all lowercase
toupper(fruits) # all uppercase
substr(fruits, 1, 3) # "App" "ban" "Che"
paste(fruits, "fruit", sep = "-") # "Apple-fruit" ...
paste0("item_", 1:3) # "item_1" "item_2" "item_3"
gsub("a", "@", fruits, ignore.case = TRUE) # replace 'a'
grepl("^[A-Z]", fruits) # TRUE FALSE TRUE