我有一个数据集,我想计算每个唯一ID相加的天数,以及两个唯一“动作”(STD,STD修改)之一期间的天数。我还想将数据显示为每个唯一ID一行。 我将如何实现这一目标?预先感谢!
所需结果:
Id Days on STD Days on STD Modified Total
123 228 0 228
321 85 42 127
数据:
structure(list(Id = c(123, 123, 321, 321, 321, 321), Action = c("STD",
"STD", "STD", "STD", "STD Modified", "STD"), IDM.Start = structure(c(1427414400,
1499299200, 1457740800, 1508371200, 1511913600, 1540166400), class = c("POSIXct",
"POSIXt"), tzone = "UTC"), IDM.End = structure(c(1438214400,
1508198400, 1458691200, 1511827200, 1515542400, 1543104000), class = c("POSIXct",
"POSIXt"), tzone = "UTC")), row.names = c(NA, 6L), class = "data.frame")
答案 0 :(得分:1)
library(tidyverse); library(lubridate)
df %>%
mutate(days = (IDM.End - IDM.Start)/ddays(1)) %>%
count(Id, Action, wt = days, name = "days") %>%
spread(Action, days, fill = 0) %>%
mutate(Total = STD + `STD Modified`)
## A tibble: 2 x 4
# Id STD `STD Modified` Total
# <dbl> <dbl> <dbl> <dbl>
#1 123 228 0 228
#2 321 85 42 127