r - 在 R 中按组计算差异 b/w 日期 - 未解决
问题描述
我试图在 R 中按组计算 b/w 最小和最大日期的差异。实现这一点的代码我在这里找到。但是,复制该示例并不会产生预期的结果。这是使用的数据集示例:
HS_Hatch <- structure(list(ClutchID = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
2L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L
), DateVisit = c("3/15/2012", "3/18/2012", "3/20/2012", "4/1/2012",
"4/3/2012", "3/18/2012", "3/20/2012", "3/22/2012", "4/3/2012",
"4/4/2012", "3/22/2012", "4/3/2012", "4/4/2012", "3/18/2012",
"3/20/2012", "3/22/2012", "4/2/2012", "4/3/2012", "4/4/2012",
"3/20/2012", "3/22/2012", "3/25/2012", "3/27/2012", "4/4/2012",
"4/5/2012"), Year = c(2012L, 2012L, 2012L, 2012L, 2012L, 2012L,
2012L, 2012L, 2012L, 2012L, 2012L, 2012L, 2012L, 2012L, 2012L,
2012L, 2012L, 2012L, 2012L, 2012L, 2012L, 2012L, 2012L, 2012L,
2012L), Survive = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -25L), .Names = c("ClutchID",
"DateVisit", "Year", "Survive"), spec = structure(list(cols = structure(list(
ClutchID = structure(list(), class = c("collector_integer",
"collector")), DateVisit = structure(list(), class = c("collector_character",
"collector")), Year = structure(list(), class = c("collector_integer",
"collector")), Survive = structure(list(), class = c("collector_integer",
"collector"))), .Names = c("ClutchID", "DateVisit", "Year",
"Survive")), default = structure(list(), class = c("collector_guess",
"collector"))), .Names = c("cols", "default"), class = "col_spec"))
这是使用 dplyr 的建议解决方案:
library(dplyr)
HS_Hatch <- HS_Hatch %>%
mutate(date_visit = as.Date(DateVisit, "%m/%d/%Y"))
exposure <- HS_Hatch %>%
group_by(ClutchID) %>%
summarize(first_visit = min(date_visit),
last_visit = max(date_visit),
exposure = last_visit - first_visit)
这是预期的结果:
ClutchID first_visit last_visit exposure
<int> <date> <date> <dbl>
1 1 2012-03-15 2012-04-03 19
2 2 2012-03-18 2012-04-04 17
3 3 2012-03-22 2012-04-04 13
4 4 2012-03-18 2012-04-04 17
5 5 2012-03-20 2012-04-05 16
这是实际结果:
first_visit last_visit exposure
1 2012-03-15 2012-04-05 21 days
似乎分组因素被忽略了。我如何让它计算每个 ClutchID 的日期差异?
解决方案
它适用于刚刚dplyr
加载。
更改summarize
为dplyr::summarize
使其明确。我建议不要使用tidyverse plyr
,因为你可以做任何事情。dplyr
推荐阅读
- vue.js - ESLint 期望在方法结束时返回一个值
- go - 从 golang 使用 AMQP 1.0 连接到 IBM MQ 时出现 EOF
- android - 如何使用 livedata 进行房间选择?
- bash - 如何将shell参数放在字符串中的字符串中?
- elasticsearch - 我可以将文本的默认类型定义为对象类型中的关键字吗?
- android - 在 Android 平台上打开本地文件的 Delphi FMX 功能失败
- php - 在 OctoberCMS 中触发 onUpdate 动作
- android - 为什么我在创建内联 mockito 模拟时会看到性能提升?
- dask - SGECluster 在多个队列中
- python - ValueError: int() 以 10 为底的无效文字:'5df1170a921ee283d8529aa3'