Is it possible to define local variables inside summarise() ?
The objective is to improve readability and avoid the output of an intermediate calculation.
I don't want to add news columns to the output and then filter them out as in the next example.
The example contains minutes where a set of people is detected asleep by a wellness tracker. The second half of summarize repeats calculations for a subset of days Mo-Fr.
I want to hide weekday, minutes* and probably sleep states if I don't see them useful by their own.
DF <-
db$minuteSleep %>%
mutate( weekday = lubridate::wday( .datetime, week_start=1 ) ) %>%
group_by( .session_id ) %>%
summarise(
s1asleep = sum( sleep_state==1 , na.rm=TRUE ),
s2restless = sum( sleep_state==2 , na.rm=TRUE ),
s3awake = sum( sleep_state==3 , na.rm=TRUE ),
minutes_inbed = n(),
minutes_total = n_distinct( lubridate::yday(.datetime) ) *24*60,
average = round( minutes_inbed/(minutes_total-minutes_inbed) *24 ,2),
quality = round( 100*s1asleep/(minutes_inbed - s3awake) ,2),
w_min_inbed = sum(weekday < 6),
w_min_total = n_distinct( lubridate::yday( .datetime[weekday < 6] ) ) *24*60,
workday_avg = round( w_min_inbed/(w_min_total-w_min_inbed) *24 ,2),
workday_qlty = round( 100*sum( sleep_state[weekday < 6]==1 , na.rm=TRUE )/(w_min_inbed - sum( sleep_state[weekday < 6]==3 , na.rm=TRUE )) ,2),
) %>%
complete(.session_id) %>%
select( -minutes_inbed, -w_min_inbed, -minutes_total, -w_min_total )