data analysis - How to Find difference between two values of last two dates in R program -
df2 date emmi act no2 2011/02/12 12345 21 11 2011/02/14 43211 22 12 2011/02/19 12345 21 13 2011/02/23 43211 13 12 2011/02/23 56341 13 12 2011/03/03 56431 18 20
i need find difference between 2 dates in column. example difference between act column values.for example, emmi 12345, difference between dates 2011/02/19 - 2011/02/12 = 21-21 = 0. want entire column of act. add new column diff , add values that. can let me know please how it.
this output want
df3 date emmi act no2 difact 2011/02/12 12345 21 11 na 2011/02/14 43211 22 12 na 2011/02/19 12345 21 13 0 2011/02/23 43211 13 12 -9 2011/02/23 56341 13 12 5
try this:
df3 <- df2 df3$difact <- ave( df3$act, df3$emmi, fun= function(x) c(na, diff(x)) )
as long dates sorted (within emmi) work, if not sorted need modify above sort within emmi first. sort entire data frame on date first (and save results of order
), run above. if need in original order can run order
on results of original order
results "unorder" data frame.
Comments
Post a Comment