Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201894

Last observation of the previous group

$
0
0

I would like to know, if I have data that I can group by a variable, how can I get the last observation of the previous group?

I have the following data:

dt <- data.table(a=c(1,1,1,2,2,2,2,2,3,3,3,3,3,3,4,4,5,5,5,5,5), b=sample.int(21))

I would like to create a new data.table that has the group ID and the difference between the last observation of the group from the last observation of the previous group. So that from the above I'd get:

   a  c
1: 1 NA
2: 2  9
3: 3  1
4: 4 -8
5: 5  5

Thanks!


Viewing all articles
Browse latest Browse all 201894

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>