stevenjoe
stevenjoe

Reputation: 339

Test Weekday then Add Number to Date in R

I've got a column with dates (df$Date) and I would like to create a new column (df$NewColumn) that adds a variable number of days depending on the day of the week (using Lubridate's wday) that is in df$Date, e.g.:

df$NewColumn <- ifelse(wday(df$Date) == 6, df$Date + 3,
                       ifelse(wday(df$Date) == 7, df$Date + 3,
                              df$Date + 2))

It is seemingly working, only problem is my date format is in a 16XXX format and I can't seem to convert it back to a proper-looking date. Thanks for your help!

Upvotes: 1

Views: 65

Answers (2)

pbaylis
pbaylis

Reputation: 1624

As stated in the comments, ifelse changes formats. If you can avoid using it, then the format should stay the same. The following code creates the output you're looking for:

library(lubridate)

df <- data.frame(Date=as.Date(c("2011/01/01",
                                "2011/01/02")))

df$NewColumn <- df$Date + 2 + as.numeric(wday(df$Date)>=6)

Upvotes: 0

Stedy
Stedy

Reputation: 7469

One way to deal with this is to use the class() function:

R> testdate <- 16716
R> class(testdate) <- "Date"
R> testdate
[1] "2015-10-08"

Upvotes: 1

Related Questions