Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate derivative diff() and keep length - add NA [duplicate]

Tags:

r

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

like image 219
Jonas Stein Avatar asked Nov 27 '12 22:11

Jonas Stein


2 Answers

Its unclear where exactly you want NA's, but you can concat them right in.

 dif <- c(NA, diff(dfrm$id, lag=1)) 
like image 85
Ricardo Saporta Avatar answered Oct 16 '22 20:10

Ricardo Saporta


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)
like image 23
RubenLaguna Avatar answered Oct 16 '22 19:10

RubenLaguna