I am looking for a function similar to diff
but instead of calculating the difference between two consecutive values, I want to compute the minimum between them. That is, If y have x <- c(7,3,17,9)
what I want is c(3,3,9)
as an output.
Is it there an implemented function to make this (not only for the minimum but also for maximum or other functions?
Explanation:
The first value (3) is the minimum between the first two elements min(c(7,3))
The second value (3) is the minimum between the second and third elements
min(c(3,17))
The third value (9) is the minimum between the third and fourth elements min(c(17,9))
Use pmin()
to calculate the minimum between each element of two or more vectors. Use head()
and tail()
to create a pair of right-sized and offset vectors.
> x = c(7,3,17,9)
> pmin(head(x, -1), tail(x, -1))
[1] 3 3 9
Two advantages over rollapply()
are that it does not require additional packages, and that the same syntax works when the vector is of length 0 and so is more robust in scripts or functions that you might hope to reuse.
> x = numeric(); pmin(head(x, -1), tail(x, -1))
numeric(0)
> x = numeric(); rollapply(x, 2, min)
Error in max(sapply(dat, length)) : invalid 'type' (list) of argument