How can I calculate the numeric derivative of a column in a data frame (with diff()) and keep the length by adding NA values?
Its unclear where exactly you want NA's, but you can concat them right in.
dif <- c(NA, diff(dfrm$id, lag=1))
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:
library(zoo)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With