I am looking for a function R to calculate the differences between consecutive or with the last non-NA value in a vector. Here is an example:
visit <- c(1,2,3,4)
time <- c(5,10,NA,15)
df <- data.frame(visit ,time)
We are looking for time since the last visit.
Using diff, we get the length of 3 vectors:
diff <- diff(df$time, lag = 1, differences = 1)
5 NA NA
Required diff vector:
5 NA 5
And ideally, it would be the same length as the original vector value, so it could be added to the dataframe 'df':
visit | time | diff
1 5 NA
2 10 5
3 NA NA
4 15 5
source
share