【问题标题】:ifelse on data frame column to replace with date time column values if matched如果匹配,数据框列上的 ifelse 将替换为日期时间列值
【发布时间】:2017-04-17 23:54:07
【问题描述】:

我需要帮助。我正在尝试根据txt_col 列的匹配值和那些不匹配的值将date_time 列值复制到新列中,标记为NA。这是我的代码:

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

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

   new_col
1477962000
1451755980
1451755980
1451755980

查看str(df) 时,date_time 列是POSIXct。我尝试转换as.numericPOSIXct,但没有成功。如果您有更优雅的方式来做我想要实现的目标,如果您分享,将不胜感激。谢谢。

【问题讨论】:

  • 它们是日期时间的数字等价物 - 自 1970-01-01 以来的秒数。用as.POSIXct() 包裹整个东西,你应该没问题。
  • 再次包装时不要忘记包含时区,当 tz 中途更改时,处理会变得非常有趣:-)
  • as.POSIXct(1477962000, origin = "1970-01-01 00:00:00") 为我工作。
  • @r2evans - 简称as.POSIXct(1477962000, origin = "1970-01-01")
  • 我偶尔会超越“显式”,谢谢。

标签: r dataframe posixct


【解决方案1】:

dplyr 封装为更严格的函数if_else,用于验证真假组件的类。为 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>

【讨论】:

    猜你喜欢
    • 2023-01-31
    • 2021-12-27
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 2012-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多