Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a Sequence of Dates For Every Date In a dataframe

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
like image 665
Jordan Wrong Avatar asked Jan 25 '26 03:01

Jordan Wrong


1 Answers

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
like image 135
M-- Avatar answered Jan 27 '26 21:01

M--