【问题标题】:maintain POSIXct time format with ifelse and dplyr and return POSIXct for both true and false使用 ifelse 和 dplyr 维护 POSIXct 时间格式,并为真假返回 POSIXct
【发布时间】:2021-09-14 17:48:12
【问题描述】:

我有一个虚拟数据框,它在 POSIXct 中包含 10 个日期时间戳。现在我想评估每一行,如果高于日期时间阈值,则将单元格值替换为不同的值,否则保留它。我使用 dplyr 包找到了一个有用的线程here,但我无法让它适用于我的特殊情况。有什么建议吗?

虚拟数据框的代码:

df<-structure(list(Date.Out = structure(c(1478699520, 1493934000, 
1510243080, 1524862800, 1541776440, 1559243220, 1475417460, 1493930940, 
1495304760, 1504640100), class = c("POSIXct", "POSIXt"), tzone = "US/Eastern")), row.names = c(6L, 
7L, 8L, 9L, 10L, 11L, 15L, 16L, 17L, 18L), class = "data.frame")

我尝试使用不起作用的 dplyr 包的代码:

df %>% 
  mutate(new =  as.POSIXct(ifelse(Date.Out>="2019-05-01 00:00:00", "2019-05-01 00:00:00", Date.Out), origin='1970-01-01', na.rm=T))

【问题讨论】:

    标签: r if-statement dplyr


    【解决方案1】:

    考虑使用case_when 而不是ifelse,因为ifelse 可以将其强制转换为整数

    library(dplyr)
    df <- df %>% 
       mutate(new = case_when(Date.Out >= as.POSIXct("2019-05-01 00:00:00")
            ~ as.POSIXct("2019-05-01 00:00:00"), TRUE ~ Date.Out))
    

    -输出

    df
            Date.Out                 new
    6  2016-11-09 08:52:00 2016-11-09 08:52:00
    7  2017-05-04 17:40:00 2017-05-04 17:40:00
    8  2017-11-09 10:58:00 2017-11-09 10:58:00
    9  2018-04-27 17:00:00 2018-04-27 17:00:00
    10 2018-11-09 10:14:00 2018-11-09 10:14:00
    11 2019-05-30 15:07:00 2019-05-01 00:00:00
    15 2016-10-02 10:11:00 2016-10-02 10:11:00
    16 2017-05-04 16:49:00 2017-05-04 16:49:00
    17 2017-05-20 14:26:00 2017-05-20 14:26:00
    18 2017-09-05 15:35:00 2017-09-05 15:35:00
    

    【讨论】:

    • 非常感谢!我知道这是代码中的一个简单修复。是的,我使用 dplyr ifelse 组合来防止返回整数。但这很好用,而且有趣的函数 case_when()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多