xyz
xyz

Reputation: 79

adding two column of a data where col1 contains date and col2 contains days

I have a data frame in which i have two columns date and days and i want to add date column with days and show the result in other column data frame-1 col date is in format of mm/dd/yyyy format

date        days
3/2/2019    8
3/5/2019    4
3/6/2019    4
3/21/2019   3
3/25/2019   7

and i want my output like this

date        days    new-date
3/2/2019    8       3/10/2019
3/5/2019    4       3/9/2019
3/6/2019    4       3/10/2019
3/21/2019   3       3/24/2019
3/25/2019   7       4/1/2019

i was trying this

as.Date("3/10/2019") +8

but i think it will work for a single value

Upvotes: 1

Views: 45

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

Convert to actual Date values and then add Days. You need to specify the actual format of date (read ?strptime) while converting it to Date.

as.Date(df$date, "%m/%d/%Y") + df$days
#[1] "2019-03-10" "2019-03-09" "2019-03-10" "2019-03-24" "2019-04-01"

If you want the output back in same format, we can use format

df$new_date <- format(as.Date(df$date, "%m/%d/%Y") + df$days, "%m/%d/%Y")

df
#       date days   new_date
#1  3/2/2019    8 03/10/2019
#2  3/5/2019    4 03/09/2019
#3  3/6/2019    4 03/10/2019
#4 3/21/2019    3 03/24/2019
#5 3/25/2019    7 04/01/2019

If you get confused with different date format we can use lubridate to do

library(lubridate)
with(df, mdy(date) + days)

Upvotes: 1

Related Questions