0

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1) Can we see the actual output of what one of your dates looks like? 2) are you opposed to using a library to handle dates? I highly recommend the [`lubridate`](https://cran.r-project.org/web/packages/lubridate/lubridate.pdf) package in R for working with dates – TaylorV Mar 19 '17 at 21:36
  • @TaylorV The date I want to copy is like "2014-05-25 12:06:18", but the output of new column is "1401019580", and type is numeric. I can use new library, but I'm a newbie in R, and don't even know which package can help me. – Megan Wenjie Song Mar 19 '17 at 21:45
  • @zx8754 There are many values in visit$A, that's why I used a for loop. I just tried ifelse, the type of new column is still a numeric, but I want it to be date. Do you know how to do it? – Megan Wenjie Song Mar 19 '17 at 21:55

1 Answers1

0

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"
zx8754
  • 52,746
  • 12
  • 114
  • 209