首页 > 解决方案 > 如何在 R 中获取三个日期的中间日期?

问题描述

我有一个包含三个日期列 x、y 和 z 的数据表,我正在尝试创建一个新列 (new_col),它是每行中三个日期的中间日期,一旦从最早到最新排列,即我想要日期在最小和最大日期之间 - 请参见下表:

X 是的 z new_col
2005 年 1 月 1 日 1998 年 5 月 4 日 2009 年 3 月 2 日 2005 年 1 月 1 日
2010 年 5 月 9 日 2003 年 2 月 14 日 2008 年 1 月 9 日 2008 年 1 月 9 日
2002 年 9 月 7 日 2010 年 12 月 8 日 2012 年 5 月 23 日 2010 年 12 月 8 日

因此,对于第 1、2 和 3 行,我分别需要 x、z 和 y 列中的日期。我怎样才能在 R 中解决这个问题?我使用过 pmin 和 pmax 但我无法将日期隔离在中间

提前致谢!

标签: rdate

解决方案


首先确保您的所有日期都是“日期”类型,您可以使用dmyfrom lubridate(假设您的数据框被称为df):

library(lubridate)

df[] <- lapply(df, dmy)

接下来,按时间顺序对每一行进行排序,并将中间列(第 2 列)作为new_col

df$new_col <- as.Date(t(apply(df, 1, sort))[,2])

最后,如果您希望结果以相同的文本格式显示(例如,“2005 年 1 月 1 日”而不是“2005-01-01”),那么您可以使用基于此答案的自定义函数:

library(dplyr)

date_to_text <- function(dates){
  dayy <- day(dates)
  suff <- case_when(dayy %in% c(11,12,13) ~ "th",
                    dayy %% 10 == 1 ~ 'st',
                    dayy %% 10 == 2 ~ 'nd',
                    dayy %% 10 == 3 ~'rd',
                    TRUE ~ "th")
  paste0(dayy, suff, " ", format(dates, "%b %Y"))
}

df[] <- lapply(df, date_to_text)

输出

             x             y             z      new_col
1 1st Jan 2005  4th May 1998  2nd Mar 2009 1st Jan 2005
2 9th May 2010 14th Feb 2003  9th Jan 2008 9th Jan 2008
3 7th Sep 2002  8th Dec 2010 23rd May 2012 8th Dec 2010

数据

df <- structure(list(x = c("1st Jan 2005", "9th May 2010", "7th Sept 2002"
), y = c("4th May 1998", "14th Feb 2003", "8th Dec 2010"), z = c("2nd Mar 2009", 
"9th Jan 2008", "23rd May 2012")), class = "data.frame", row.names = c(NA, 
-3L))
               

推荐阅读