Reputation: 77
I would like to insert rows based on the values in a column by groups. For example, in the following example, I have two observations for group A and one observation for group B. And I am interested in creating the output data frame. Output data frame include 2days before and after the date in the input data frame. (e.g., Group A (100-2,100-1,100,100+1,100+2))
Input:
Group Date
A 100
A 15
B 35
Output
Group Date
A 98
A 99
A 100
A 101
A 102
A 13
A 14
A 15
A 16
A 17
B 33
B 34
B 35
B 36
B 37
Upvotes: 1
Views: 104
Reputation: 887108
We can use data.table
library(data.table)
setDT(df1)[, .(Date = seq((Date-2), Date+2, by = 1)), .(Group, n = 1:nrow(df1))
][, n := NULL][]
# Group Date
# 1: A 98
# 2: A 99
# 3: A 100
# 4: A 101
# 5: A 102
# 6: A 13
# 7: A 14
# 8: A 15
# 9: A 16
#10: A 17
#11: B 33
#12: B 34
#13: B 35
#14: B 36
#15: B 37
Upvotes: 1