Warrior
Warrior

Reputation: 223

Create a new column in a dataframe that includes the two years after a given date

I would like to add a column of date in a dataframe. The column would include the current date and the the same day for the next two years. For example, consider dataframe df

Date      Index Group
12/31/2012  A   1
12/31/2013  B   1
12/31/2014  B   2

I want to change the column of Date to the following df2

Date    Index   Group
12/31/2012  A   1
12/31/2013  A   1
12/31/2014  A   1
12/31/2013  B   1
12/31/2014  B   1
12/31/2015  B   1
12/31/2014  B   2
12/31/2015  B   2
12/31/2016  B   2

This is what I have tried:

library(lubridate)
library(dplyr)

df2 = df1 %>% mutate(Date = Date + years(2))

Upvotes: 1

Views: 29

Answers (1)

ashwin agrawal
ashwin agrawal

Reputation: 1611

Below is the solution:

Generated data:

example<-data.frame( Date = c("12/31/2012", "12/31/2013", "12/31/2014"), index = c("A", "B", "B"), group = c(1,1,2))
print(example)

output

        Date index group
1 2012-12-31     A     1
2 2013-12-31     B     1
3 2014-12-31     B     2

Solution Code:

library(lubridate)
library(dplyr)


example[,1]<-mdy(example[,1])
df1<-example %>% mutate(Date = Date%m+% years(1))
df2<-example %>% mutate(Date = Date%m+% years(2))
final_df<-rbind(example,df1,df2)
print(final_df)

output

        Date index group
1 2012-12-31     A     1
2 2013-12-31     B     1
3 2014-12-31     B     2
4 2013-12-31     A     1
5 2014-12-31     B     1
6 2015-12-31     B     2
7 2014-12-31     A     1
8 2015-12-31     B     1
9 2016-12-31     B     2

Upvotes: 1

Related Questions