Skip to content

vector

Create

Action Code Details
Define vector
c(1, 2, 3)
Define with n repeated values v
rep(v, n)
Define with n repeated values v
rep_len(v, n)
Zeros, length n
numeric(n)
NaNs, length n
NaN[1:n]
Sequence from a to b
seq(a, b)
Sequence between a to b of length n
seq(a, b, length.out=n)

Test

Action Code Details
Is vector
is.vector(x) && is.atomic(x)
is.vector() returns true for lists as well!
Is empty
length(x) == 0
Contains value v
v %in% x
Contains NA value(s)
anyNA(x)
Contains each of the values in vector v
all(v %in% x)
Does not contain value v
!(v %in% x)

Extract

Action Code Details
Length
length(x)
First element
x[1]
Last element
data.table::last(x)
Last element
tail(x, 1)

Aggregate

Action Code Details
Sum elements
sum(x)
Mean of elements
mean(x)
Mode
table(x) %>% sort() %>% names() %>% last()
Mode of positive integers 1:K
tabulate(x) %>% which.max()
Compute function per group, as list
tapply(x, INDEX = rep_len(1:2, length(x)), mean)
Outputs a list with the results per group

Indexing

Action Code Details
TRUE values
which(x)
FALSE values
which(!x)
Index of smallest value
which.min(x)
Index of largest value
which.max(x)

Derive

Order

Action Code Details
Sort descending
sort(x)
Reverse
rev(x)
Shuffle
sample(x)

Map

Element-wise operations

Action Code Details
If-else with constant results
ifelse(x == TRUE, 1, 0)
If-else with element-specific results
ifelse(x, seq(-1, -100, by=-1), 1:100)
Replace NAs by zeros
ifelse(is.na(x), 0, x)
Replace specific values by zeros
ifelse(x %in% values, 0, x)
Replace elements at index with given values
replace(x, c(2, 4), c(NA, Inf))
Order by value, breaking ties with further args
order(x)
Ranking, with ties option
rank(x, ties='first')
Clip values below a
pmin(x, a)
Clip values above b
pmax(x, b)
Find pairwise min between two vectors
pmin(x, y)
Find pairwise max between two vectors
pmax(x, y)
Discretize values into bin number
findInterval(1:4, c(0, 2, 4))
Discretize values into n levels
cut(x, n)
Discretize values in specified intervals
cut(x, breaks)
Linear interpolation
approxfun(x, method='linear')(x2)
Spline interpolation
splinefun(x)(x2)
Smoothing spline interpolation
smooth.spline(x) %>% predict(x2)

Grow

Action Code Details
Repeat vector n times
rep(x, n)
Repeat vector up to length n
rep_len(x, n)

Shrink

Action Code Details
Exclude NA
na.exclude(x)
Exclude NA
x[!is.na(x)]
Exclude NA
Filter(Negate(is.na), x)
Exclude non-finite values
x[is.finite(x)]
Exclude non-finite values
Filter(is.finite, x)
Lagged difference
diff(x)
Sample n elements
sample(x, n)

Convert

Action Code Details
Split into a list of vectors, according to a grouping vector
split(x, g)
Can be undone by unsplit(y, g)
Running-length encoding
rle(x)