I am literally stuck on this. The df1
has the following variables:
serial
= Group of people
id1
= th
We can use rleid
from data.table
to get the 'Occurance' correct
library(data.table)
wkdays <- c("Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday")
out1 <- do.call(rbind, Map(function(x, y) {
i1 <- match(y, wkdays): length(x)
i2 <- x[i1] != 0
i3 <- all(i2)
grp1 <- rleid(i2)
Days <- if(i3) tapply(names(x)[i1][i2], grp1[i2], FUN = paste, collapse= ' ') else ''
Occurance <- if(i3) length(grp1[i2]) else 0
data.frame(Occurance, Days)
}, asplit(df[-(1:3)], 1), df$Day))
out1$Duration <- rowSums(df1[startsWith(names(df1), 'day')])
out1
# Occurance Days Duration
#1 7 day1 day2 day3 day4 day5 day6 day7 11
#2 0 12
#3 5 day3 day4 day5 day6 day7 18