Sairam Reddipalli Sairam Reddipalli - 1 month ago 5
R Question

add incrimental dates in a dataframe by the condition in R

Cheers, I have a data frames with the following structure.
Week_Start_Date is the start day of the week(Sunday).

DF1:
Week_Start_Date Event Days
2016-08-14 Independence 4
2016-01-24 Republic 3


I would like to alter DF1 (Increment the dates by a day till Days column). Eg: Independence is celebrated for 4 days staring from 2016-08-14 (Week_Start_Date) till 2016-08-17.

DF2:
Week_Start_Date Event Days
2016-08-14 Independence 1
2016-08-15 Independence 2
2016-08-16 Independence 3
2016-08-14 Independence 4
2016-01-24 Republic 1
2016-01-25 Republic 2
2016-01-26 Republic 3


I'm using 'dplyr' package and I tried, unsuccessfully, with:

DF2 <- rbind(DF1, DF1 %>%
mutate(Week_Start_Date = Week_Start_Date + 1:Days, Event=Event, Days = 1:Days))


Can anyone point me to right direction?

Note:

str(DF1$Week_Start_Date): Date, format: "2016-08-04"

Answer

A solution in base R:

# Sample data
DF1 <- cbind.data.frame(
    Week_Start_Date = c(as.Date("2016-08-14"), as.Date("2016-01-24")),
    Event = c("Independence", "Republic"),
    Days = c(4,3),
    stringsAsFactors = FALSE);

# Apply per row, create list and rbind entries
lst <- apply(DF1, 1, function(x) 
    cbind.data.frame(
        Week_Start_Date = as.Date(x["Week_Start_Date"]) + seq(0, as.numeric(x["Days"]) - 1),
        Event = x["Event"],
        Days = seq(1, as.numeric(x["Days"])),
        row.names = NULL));
df <- do.call(rbind, lst);

# Output
print(df);
  Week_Start_Date        Event Days
1      2016-08-14 Independence    1
2      2016-08-15 Independence    2
3      2016-08-16 Independence    3
4      2016-08-17 Independence    4
5      2016-01-24     Republic    1
6      2016-01-25     Republic    2
7      2016-01-26     Republic    3
Comments