Jonas Stein - 5 months ago 47

R Question

How can I calculate the numeric derivative of a column in a data frame (with diff())

and keep the length by adding NA values?

Answer

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)
```