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

為{幸葍}努か 提交于 2019-12-06 07:53:58

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!