如果匹配,则将数据框列上的ifelse替换为日期时间列值

时间:2017-04-17 23:54:08

标签: r dataframe posixct

我需要帮助。我正在尝试根据date_time列的匹配值和未匹配的值txt_colNA列值复制到新列中。这是我的代码:

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

但是,我在新列中获取数字,而不是日期时间:

   new_col
1477962000
1451755980
1451755980
1451755980

查看str(df)时,列date_timePOSIXct。我尝试转换as.numericPOSIXct,但它无效。如果您有更优雅的方式来实现我想要实现的目标,那么如果您分享,将非常感激。谢谢。

1 个答案:

答案 0 :(得分:6)

dplyr包作为更严格的函数if_else,验证true和false组件的类。明确地提供NA值的类使得这更加“类型安全”

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>
相关问题