База R Решение:
df$grouping_var <- paste(df$host_id, as.Date(df$date, "%m-%Y"), sep = "_")
count_df <- data.frame(do.call("rbind", lapply(split(df, df$grouping_var),
function(x){
tmp <- data.frame(t(tapply(x$room_type_NV, x$room_type_NV, length)))
return(cbind(x, data.frame(tmp[rep(seq_len(nrow(tmp)), nrow(x)), ], row.names = NULL)))
}
)
),
row.names = NULL
)
Данные:
structure(list(id = c(2, 1, 3, 1, 2, 3, 1, 2, 1, 2), date = structure(c(16983,
16983, 16983, 17014, 17014, 17014, 17045, 17045, 17106, 17106
), class = "Date"), host_id = c(27280608, 27280608, 27280608,
27280608, 27280608, 27280608, 27280608, 27280608, 27280608, 27280608
), room_type_NV = structure(c(2L, 1L, 1L, 1L, 2L, 1L, 1L, 2L,
1L, 2L), .Label = c("Entire home", "Shared home"), class = "factor"),
grouping_var = c("27280608_2016-07-01", "27280608_2016-07-01",
"27280608_2016-07-01", "27280608_2016-08-01", "27280608_2016-08-01",
"27280608_2016-08-01", "27280608_2016-09-01", "27280608_2016-09-01",
"27280608_2016-11-01", "27280608_2016-11-01")), row.names = c(NA,
-10L), class = "data.frame")