我有三个日期列(类日期(,我想创建一个新列,它将具有这三个日期中最早的一个。这是我在下面使用的代码:
df1 <- df %>% mutate(timeout= pmin(date1, date2, end_date))
如果date1
和date2
是NA
s,那么我希望在timeout
列中返回end_date
中的日期,因此timeout
不应该有任何NA
s。上面的代码将带回NA
s。如有任何帮助,我们将不胜感激。
您可以添加na.rm = TRUE
,然后在计算pmin
时,它将忽略每行中的NA
s。
library(dplyr)
df %>%
mutate(timeout = pmin(date1, date2, end_date, na.rm = TRUE))
输出
id date1 date2 end_date timeout
1 1 <NA> <NA> 2008-01-23 2008-01-23
2 1 2007-10-16 2007-11-01 2008-01-23 2007-10-16
3 2 2007-11-30 2007-11-30 2007-11-30 2007-11-30
4 3 2007-08-17 2007-12-17 2008-12-12 2007-08-17
5 3 2008-11-12 2008-12-12 2008-12-12 2008-11-12
数据
df <- structure(list(id = c(1L, 1L, 2L, 3L, 3L), date1 = structure(c(NA,
13802, 13847, 13742, 14195), class = "Date"), date2 = structure(c(NA,
13818, 13847, 13864, 14225), class = "Date"), end_date = c("2008-01-23",
"2008-01-23", "2007-11-30", "2008-12-12", "2008-12-12")), class = "data.frame", row.names = c("1",
"2", "3", "4", "5"))