I am having problems with reactively passing date-time
collapsing functions into index_by
function from package tsibble
.
index_by
takes as an argument a time function
(for example week()
or month()
from lubridate
) and collapses the data accordingly.
I want the collapsing to be reactive to user input (specifically selected data-range).
Example: if selected date-range > 60
, collapse using week()
, if selected date-range > 120
, collapse using month()
.
EDIT: I am specifically refering to using tsibble in the context of server side of shiny module for plotting. Example:
mod_plot = function(input, output, session, df, date_Range){
output$plot = renderPlotly({
df() %>%
index_by(collapse_time = week(.)/month(.)) %>%
summarise(trace1 = sum(trace1))%>%
plot_ly(type = 'bar', x = ~collapse_time, y = ~trace1)
})
}
In order to avoid code duplicity, it would be great to somehow pass date collapsing functions into index_by. Example using tibbletime:
mod_plot = function(input, output, session, df, date_Range){
output$plot = renderPlotly({
#create reactive variable collapse_time based on selected time range
collapse_time = renderText(if(as.numeric(date_Range$selectdateRange[2] - date_Range$selectdateRange[1]) <= 60){"daily"}
else if(as.numeric(date_Range$selectdateRange[2] - date_Range$selectdateRange[1]) < 120){"weekly"}
else{"monthly"})
df() %>%
collapse_by(collapse_time ) %>%
group_by(date) %>%
summarise(trace1 = sum(trace1))%>%
plot_ly(type = 'bar', x = ~date, y = ~trace1)
})
}
This allows for concise and readable pipeline.
This custom function returns desired collapsing function based on selected date-range.
get_fct =
function(x){
if(date_Range$selectdateRange[2] - date_Range$selectdateRange[1] <= 60){
ymd
}
else if(date_Range$selectdateRange[2] - date_Range$selectdateRange[1] < 120){
yearweek
}
else if(date_Range$selectdateRange[2] - date_Range$selectdateRange[1] >= 120){
yearmonth}
}
collapsing_function = get_fct(x = as.numeric(date_Range$selectdateRange[2] - date_Range$selectdateRange[1]))