I have to calculate the increments of a variable m
for a time interval (t2-t1).
Here is a dummy version of my data frame:
df <- expand.grid(m = do.breaks(c(1, 10), 5),
sample = c("A", "B", "C", "D"))
df$t <- rep(1:6, 4, ordered = TRUE)
df$d_m <- NA
what I'm trying to do is to populate df$d_m[i]
with the difference between df$m[i+1]
and df$m[i]
,
also this has to be done within each level of sample.
So this is my attempt, but is not successful at all.
delta_m <- function(m, t){
for(i in 1:length(t)){
df$d_m[i] <- m[i+1] - m[i]
}}
df <- ddply(df, .(sample, t), transform, d_m = delta_m(m, t))
Where am I wrong?