Jonas Stein Jonas Stein - 1 month ago 7x
R Question

Calculate derivative diff() and keep length - add NA

How can I calculate the numeric derivative of a column in a data frame (with diff())
and keep the length by adding NA values?


From this answer to a question of mine.

If you were looking for a generic way to prepend NA

pad  <- function(x, n) {
    len.diff <- n - length(x)
    c(rep(NA, len.diff), x) 

x <- 1:10
dif <- pad(diff(x, lag=1), length(x)) 

but if you are not afraid to bring in zoo library it's better to do:

x <- 1:5
as.vector(diff(zoo(x), na.pad=TRUE)) # convert x to zoo first, then diff (that invokes zoo's diff which takes a na.pad=TRUE)
# NA 1 1 1 1 (same length as original x vector)