Apologies if this has been asked before, but I couldn't find any question which answers this exactly. I have a data like this:
Project Date price
A 30/3/2013 2082
B 19/3/2013 1567
B 22/2/2013 1642
C 12/4/2013 1575
C 5/6/2013 1582
I want to have a column with last-instance prices by group. For example, for row 2, the last instance price for same group will be 1642. The final data will look somewhat like this:
Project Date price lastPrice
A 30/3/2013 2082 0
B 19/3/2013 1567 1642
B 22/2/2013 1642 0
C 12/4/2013 1575 0
C 5/6/2013 1582 1575
How to do this? The main issue I'm facing is that the data may not be ordered by date so its not as if I can just take the last cell.
Here's an option. I'd also recommend to use
NA
s instead if0
because0
could be actual price.Another option is to use
shift
from the devel version ofdata.table
Or with base R
As a side note, it is better to keep your date column in a
Date
class in the first place, so I'd recommend doingdf$Date <- as.Date(df$Date, format = "%d/%m/%Y")
once and for all.