Lil*_*ilu 2 r dataframe posixct
我需要帮助.我试图date_time根据列的匹配值txt_col和不匹配的值将列值复制到新列中NA.这是我的代码:
df$new_col <- ifelse(df$txt_col == "apple", df$date_time, NA)
Run Code Online (Sandbox Code Playgroud)
但是,我在新列中获取数字,而不是日期时间:
new_col
1477962000
1451755980
1451755980
1451755980
Run Code Online (Sandbox Code Playgroud)
在查看时str(df),列date_time是POSIXct.我试图转换as.numeric和POSIXct,也没有工作.如果你有更优雅的方式去做我想要实现的目标,那么如果你分享,我们将不胜感激.谢谢.
打包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>
Run Code Online (Sandbox Code Playgroud)