Вот как вы можете сделать это с пакетами dplyr
и lubridate
-
library(dplyr)
library(lubridate)
df$week_year <- paste(week(df$date), year(df$date), sep = "-")
filter(df, modality == "HD") %>%
group_by(id, name, week_year) %>%
summarise(sessions = n()) %>%
group_by(id, name) %>%
summarize(avg_sessions_per_week = mean(sessions))
# A tibble: 3 x 3
# Groups: id [?]
# id name avg_sessions_per_week
# <int> <chr> <dbl>
# 1 10101650 name1 3.00
# 2 10205987 name3 2.80
# 3 10206042 name2 3.00
Данные -
df <- structure(list(id = c(10101650L, 10101650L, 10101650L, 10101650L,
10101650L, 10101650L, 10101650L, 10101650L, 10101650L, 10101650L,
10101650L, 10101650L, 10101650L, 10206042L, 10206042L, 10206042L,
10206042L, 10206042L, 10206042L, 10206042L, 10206042L, 10206042L,
10206042L, 10206042L, 10206042L, 10101650L, 10101650L, 10101650L,
10101650L, 10101650L, 10101650L, 10101650L, 10101650L, 10101650L,
10101650L, 10101650L, 10101650L, 10101650L, 10101650L, 10205987L,
10205987L, 10205987L, 10205987L, 10205987L, 10205987L, 10205987L,
10205987L, 10205987L, 10205987L, 10205987L, 10205987L, 10205987L,
10205987L, 10206042L, 10206042L, 10206042L, 10206042L, 10206042L,
10206042L, 10206042L, 10206042L, 10206042L, 10206042L, 10206042L,
10206042L), name = c("name1", "name1", "name1", "name1", "name1",
"name1", "name1", "name1", "name1", "name1", "name1", "name1",
"name1", "name2", "name2", "name2", "name2", "name2", "name2",
"name2", "name2", "name2", "name2", "name2", "name2", "name1",
"name1", "name1", "name1", "name1", "name1", "name1", "name1",
"name1", "name1", "name1", "name1", "name1", "name1", "name3",
"name3", "name3", "name3", "name3", "name3", "name3", "name3",
"name3", "name3", "name3", "name3", "name3", "name3", "name2",
"name2", "name2", "name2", "name2", "name2", "name2", "name2",
"name2", "name2", "name2", "name2"), date = structure(c(9223,
9225, 9227, 9230, 9232, 9234, 9237, 9239, 9241, 9242, 9244, 9246,
9248, 9223, 9225, 9227, 9230, 9232, 9234, 9237, 9239, 9241, 9244,
9246, 9248, 9251, 9253, 9255, 9258, 9260, 9262, 9265, 9267, 9269,
9272, 9274, 9276, 9279, 9281, 9251, 9253, 9255, 9258, 9260, 9262,
9265, 9267, 9269, 9272, 9274, 9276, 9279, 9281, 9251, 9253, 9255,
9258, 9260, 9262, 9265, 9267, 9269, 9272, 9274, 9276), class = "Date"),
modality = c("HD", "HD", "HD", "HD", "HD", "HD", "HD", "HD",
"HD", "HD", "HD", "HD", "HD", "HD", "HD", "HD", "HD", "HD",
"HD", "HD", "HD", "HD", "HD", "HD", "HD", "HD", "HD", "HD",
"HD", "HD", "HD", "HD", "HD", "HD", "HD", "HD", "HD", "HD",
"HD", "HD", "HD", "HD", "HD", "HD", "HD", "HD", "HD", "HD",
"HD", "HD", "HD", "HD", "HD", "HD", "HD", "HD", "HD", "HD",
"HD", "HD", "HD", "HD", "HD", "HD", "HD")), .Names = c("id",
"name", "date", "modality"), row.names = c(NA, -65L), class = "data.frame")