r - 如何在 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 但我无法将日期隔离在中间
提前致谢!
解决方案
首先确保您的所有日期都是“日期”类型,您可以使用dmy
from 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))
推荐阅读
- mysql - 在 MySQL 中创建此触发器时如何修复此错误?
- javascript - (.SVG,.PNG)未加载到反应组件中
- python - 将响应对象中的图像保存为python中的文件
- maven - 如何使用 IntelliJ 和 Maven 构建 Gatling 脚本?
- java - 向kafka dlq发送错误消息时获取ClassCastException
- bash - 在 awk 脚本头中指定其他标志
- sql - oracle如何调用函数
- python-3.x - 如何在变量表中创建一个空列表以在关键字表中使用它?
- linux - 为什么这个简单的 Makefile 会陷入无限循环?
- android - 如何提高 ScrollView 的性能?