Reputation: 730
I'm trying to add and subtract days from my date-time but facing some issues.
Reproducible Example
df = data.frame(date1=c("2017-07-07", "2017-02-11", "2017-05-22"))
library(lubridate)
df$date1 <- ymd(df$date1) + years(2)
df$day <- wday(df$date1, label=TRUE)
df$date1 <- as.Date(df$date1, "%Y-%m-%d")
df$day <- as.character(df$day)
Data
date1 day
1 2019-07-07 Sun
2 2019-02-11 Mon
3 2019-05-22 Wed
Problem
I'm trying to get my code to work in a manner that when the day is "Sunday", it will simply copy the same date. However, my code above returns "18084" instead of "2019-07-07".
Could someone explain to me where my issue is?
library(dplyr)
df %>% mutate(newdate = ifelse(day == "Sun", as.Date(as.character(date1), "%Y-%m-%d"), 1))
date1 day newdate
1 2019-07-07 Sun 18084
2 2019-02-11 Mon 1
3 2019-05-22 Wed 1
Upvotes: 2
Views: 42
Reputation: 388982
The issue is you are trying to return objects of two different class in ifelse
. If you check
str(df)
#'data.frame': 3 obs. of 2 variables:
# $ date1: Date, format: "2019-07-07" "2019-02-11" "2019-05-22"
# $ day : chr "Sun" "Mon" "Wed"
So date1
is of class "Date" and the else part in your ifelse
contains 1 which is numeric. So now to bring both of them to the same class what R does is
as.numeric(as.Date("2019-07-07"))
#[1] 18084
Dates are anyway represented internally as numbers. For example,
as.Date(18084, origin = "1970-01-01") #would give
#[1] "2019-07-07"
What you probably need is
library(dplyr)
df %>% mutate(newdate = ifelse(day == "Sun", as.character(date1), "1"))
# date1 day newdate
#1 2019-07-07 Sun 2019-07-07
#2 2019-02-11 Mon 1
#3 2019-05-22 Wed 1
but this will change newdate
to character class.
Upvotes: 2