如果匹配,则在数据框列上使用ifelse替换为日期时间列值 [英] ifelse on data frame column to replace with date time column values if matched
问题描述
我需要帮助。我正在尝试根据 txt_col
列的匹配值将 date_time
列值复制到新列中匹配标记为 NA
。这是我的代码:
I need help. I am trying to copy the date_time
column values into new column based on matching values of txt_col
column and those that are not matched mark as NA
. Here is my code:
df$new_col <- ifelse(df$txt_col == "apple", df$date_time, NA)
但是,我在新列中得到数字,而不是日期时间:
However, I get numbers in the new column, instead of date-time :
new_col
1477962000
1451755980
1451755980
1451755980
查看 str(df)
时,列 date_time
是 POSIXct
。我试图将 as.numeric
和 POSIXct
转换,但是没有用。如果您有更优雅的方式来完成我要达到的目标,那么如果您分享的话,将不胜感激。谢谢。
When looking at the str(df)
, the column date_time
is POSIXct
. I tried to convert as.numeric
and POSIXct
, it didn't work. If you have more elegant ways to do what I am trying to achieve, it would be much appreciated if you share. Thank you.
推荐答案
将 dplyr
打包为更严格的功能 if_else
验证true和false组件的类。显式提供NA值的类别使此类型更加安全
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>
这篇关于如果匹配,则在数据框列上使用ifelse替换为日期时间列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!