Lilu
Lilu

Reputation: 108

ifelse on data frame column to replace with date time column values if matched

I need help. I am trying to copy the date_time column values into new column based on matching values of txt_col column and those that are not matched mark as NA. Here is my code:

df$new_col <- ifelse(df$txt_col == "apple", df$date_time, NA)

However, I get numbers in the new column, instead of date-time :

   new_col
1477962000
1451755980
1451755980
1451755980

When looking at the str(df), the column date_time is POSIXct. I tried to convert as.numeric and POSIXct, it didn't work. If you have more elegant ways to do what I am trying to achieve, it would be much appreciated if you share. Thank you.

Upvotes: 2

Views: 1441

Answers (1)

Andrew Lavers
Andrew Lavers

Reputation: 4378

Package dplyr as a stricter function if_else that verifies the classes of both the true and false components. Explicitly providing the class for the NA value makes this more "type safe"

library(dplyr)
df <- data.frame(txt_col = c("apple", "apple", "orange"),
                 date_time = as.POSIXct(c("2017-01-01", "2017-01-02", "2017-01-03")))

# use dplyr::if_else instead, and provide explicit class
df$new_col <- if_else(df$txt_col == "apple", df$date_time, as.POSIXct(NA))

df
#   txt_col  date_time    new_col
# 1   apple 2017-01-01 2017-01-01
# 2   apple 2017-01-02 2017-01-02
# 3  orange 2017-01-03       <NA>

Upvotes: 7

Related Questions