I have a data frame that has two columns, Ticker and Date. For every Date observation, I would like to create a sequence of dates that goes back 3 days from the original date to the original date (like seq(OriginalDate, OriginalDate-3, by=1))
For example:
df = data.frame(Ticker = c("AAPL", "MSFT"), Date = c("2019-01-05", "2019-02-10"))
print(df)
Ticker Date
AAPL 2019-01-05
MSFT 2019-02-10
I would like the new data frame to look like this:
print(df)
Ticker Date Date_Sequence
AAPL 2019-01-05 2019-01-05 #original Date
AAPL 2019-01-05 2019-01-04 #original Date -1
AAPL 2019-01-05 2019-01-03 #original Date -2
MSFT 2019-02-10 2019-02-10
MSFT 2019-02-10 2019-02-09
MSFT 2019-02-10 2019-02-08
Using data.table:
library(data.table)
setDT(df)[ , .(Date_Sequence = as.Date(Date) - 0:2), .(Ticker, Date)]
# Ticker Date Date_Sequence
# 1: AAPL 2019-01-05 2019-01-05
# 2: AAPL 2019-01-05 2019-01-04
# 3: AAPL 2019-01-05 2019-01-03
# 4: MSFT 2019-02-10 2019-02-10
# 5: MSFT 2019-02-10 2019-02-09
# 6: MSFT 2019-02-10 2019-02-08
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With