Random data. You said that "month and hour are attributes in the dataset", so I'll first generate random data over one year, then I'll take that POSIXt
time to generate the two columns of $month
and $hour
. (They'll be strings, but it doesn't matter.) After those are made, we no longer need or use $when
.
set.seed(42)
crimes0 <- data.frame(when = as.POSIXct('2020-01-01 00:00:00', tz="UTC") + runif(100000, min = 0, max = 365*24*3600))
head(crimes0)
# when
# 1 2020-11-29 21:42:03
# 2 2020-12-08 00:46:50
# 3 2020-04-14 10:34:56
# 4 2020-10-30 02:43:16
# 5 2020-08-22 05:41:26
# 6 2020-07-08 11:16:49
range(crimes0$when)
# [1] "2020-01-01 00:04:19 UTC" "2020-12-30 23:56:02 UTC"
crimes0 <- within(crimes0, {
month = format(when, format = "%b")
hour = format(when, format = "%H")
})
head(crimes0)
# when hour month
# 1 2020-11-29 21:42:03 21 Nov
# 2 2020-12-08 00:46:50 00 Dec
# 3 2020-04-14 10:34:56 10 Apr
# 4 2020-10-30 02:43:16 02 Oct
# 5 2020-08-22 05:41:26 05 Aug
# 6 2020-07-08 11:16:49 11 Jul
Finding the most frequent occurrences.
sort(table(crimes0$month), decreasing = TRUE)
# Jul May Jan Oct Mar Dec Aug Nov Sep Jun Feb Apr
# 8623 8543 8539 8456 8429 8346 8319 8294 8242 8193 8073 7943
sort(table(crimes0$hour), decreasing = TRUE)
# 01 23 14 05 07 09 03 06 00 15 21 10 02 16 11 18 13 12 17 19 20 22 04 08
# 4264 4246 4239 4237 4231 4227 4217 4214 4207 4193 4193 4189 4171 4171 4147 4124 4107 4102 4100 4093 4092 4082 4080 4074
Now adapt that to something that might work in a shiny app. I'm assuming that either (a) the data itself is reactive, or (b) there is other filtering of the data such that your counts are reactive and will change. For example, if the user is given the choice of filtering the types of crimes to drill down into, then the two value boxes would depict the most frequent month/hour for that type.
library(shiny)
library(shinydashboard)
# if this is shiny, then the data is or should be something reactive ...
# I'll assume that 'crimes' is reactive data
crimes_rx <- reactive({
# ...
crimes0
})
crimes_freq <- reactive({
dat <- req(crimes_rx())
list(
month = sort(table(dat$month), decreasing = TRUE),
hour = sort(table(dat$hour), decreasing = TRUE)
)
})
output$value1 <- renderValueBox({
req(crimes_freq())
valueBox(
names(crimes_freq()$month)[1]
,'The month including most records'
,icon = icon("gbp",lib='glyphicon')
,color = "navy")
})
output$value2 <- renderValueBox({
req(crimes_freq())
valueBox(
names(crimes_freq()$hour)[1]
,'The hour including most records'
,icon = icon("gbp",lib='glyphicon')
,color = "navy")
})
For your own shiny app, make sure that this crimes_rx
is the data you want summarized in the value boxes. (If you are using static data, then just use crimes_rx <- reactive({ crimes })
or remove that and replace all references of dat$
by crimes$
in crimes_freq
.)