Q:

Create a new column of type date from another column of type date

I'm trying to create a new column of type date from another column of type date in the same table.
My code is like this:
A <- c(1,2)
B <- c(as.POSIXct("2014-04-28 03:01:09"),NA)
C <- c(as.POSIXct(NA), as.POSIXct("2014-05-17 03:17:00"))
df <- data.frame(A,B,C)
df$D <- ifelse(A == 1, B, C)    

Then the value of D is 1398668469, 1400311020, instead of date.
How can I make the type of D also date?

A:

Either restore the class after ifelse or use dplyr::if_else()
# using ifelse and restore class
df$D <- ifelse(A == 1, B, C)  
class(df$D) <- class(df$B)

# or use dplyr if_else
library(dplyr)
df <- df %>% mutate(D_v1 = if_else(A == 1, B, C))

str(df)
# 'data.frame': 2 obs. of  5 variables:
# $ A   : num  1 2
# $ B   : POSIXct, format: "2014-04-28 03:01:09" NA
# $ C   : POSIXct, format: NA "2014-05-17 03:17:00"
# $ D   : POSIXct, format: "2014-04-28 03:01:09" "2014-05-17 03:17:00"
# $ D_v1: POSIXct, format: "2014-04-28 03:01:09" "2014-05-17 03:17:00"

