Group_by, summarise reactivity not working in R Shiny - shiny

Reactivity is working everywhere else in my app, but when I try to create a summary statistic table the table returns the name of the variable selected instead of the summary statistic:
ui <- selectInput('summary_metric', 'Select Metric', choices = c('height', 'weight'))
tableOuput('summary_table')
server <- function(input, output) {
output$summary_table <- renderTable({ data %>% group_by(Age_Group) %>%
summarise(min = min(input$summary_metric),
median = median(weight))})
Returns a table that reads:
Age_Group
min
median
18-29
weight
170
30-39
weight
180
40-49
weight
190
when 'weight' is selected in the UI and toggles to 'height' in the min column when 'height' is selected in the UI. So instead of calculating the minimum, it is just returning the variable name. Any thoughts as to what I'm missing?

Related

checkboxGroupInput in Shiny doesn't work when input data is data table not data frame

I have a case where I need to view a data table in Shiny with dynamic user-selected columns to view. This demo in Shiny Gallery was very insightful as a start. But when I applied it to my specific code where I use a data table rather than a data frame the main panel throws an error of "'data' must be 2-dimensional (e.g. data frame or matrix)". The only reason I got figure out for this error is that the input$show_vars does not work when the input data is a data table.
I present here two samples of codes to show the problem. The first one works well when the diamonds data is a data frame. The other one is the same code but the diamonds table is converted in data table in server section.
Appreciate any assistance to fix the code such that it works well when the input data is data table class.
Scenario1:
library(shiny)
library(ggplot2) # for the diamonds dataset
ui <- fluidPage(
title = "Examples of DataTables",
sidebarLayout(
sidebarPanel(
checkboxGroupInput("show_vars", "Columns in diamonds to show:",
names(diamonds), selected = names(diamonds))
),
mainPanel(
tabsetPanel(
tabPanel("diamonds", DT::dataTableOutput("mytable1")),
)
)
)
)
server <- function(input, output) {
# choose columns to display
diamonds2 = diamonds[sample(nrow(diamonds), 1000), ]
output$mytable1 <- renderDataTable({
diamonds2[, input$show_vars]
})
}
shinyApp(ui, server)
`
Scenario2:
library(shiny)
library(ggplot2) # for the diamonds dataset
ui <- fluidPage(
title = "Examples of DataTables",
sidebarLayout(
sidebarPanel(
checkboxGroupInput("show_vars", "Columns in diamonds to show:",
names(diamonds), selected = names(diamonds))
),
mainPanel(
tabsetPanel(
tabPanel("diamonds", DT::dataTableOutput("mytable1")),
)
)
)
)
server <- function(input, output) {
# choose columns to display
diamonds2 = as.data.table(diamonds[sample(nrow(diamonds), 1000), ])
output$mytable1 <- renderDataTable({
diamonds2[, input$show_vars]
})
}
shinyApp(ui, server)

How can I refer to column created in var dynamically?

I have created a pareto analysis but the problem is that it's not dynamic because the rankx it's done in a calculated column in customers table in order of the sum of sales in an other table.
Now my #runningtotal is
CALCULATE([M-CY_Sales];FILTER(ALLSELECTED(CUSTOMERS);
CUSTOMERS[DAX RANK]<=MAX(CUSTOMERS[DAX RANK]));CUSTOMERS[Customer Number] <>BLANK();
'Detail Sales Report'[Total Actual Revenue - Base]>0)
where I use the calculated column with rankx CUSTOMERS[DAX RANK]. Can I make this measure dynamic? I was thinking to build a table with var and addcoloumn but I'm not able to do it. My actual problem is that I need this pareto dynamic because the filter for district does not function with static column.
I was trying to write something but I don't know how I could create what I want
#RUNNINGTOTAL2 =
var customerranked=ADDCOLUMNS(ALLSELECTED(CUSTOMERS);"ranking";[M-DAX RANK])
return
CALCULATE([M-CY_Sales];FILTER(ALLSELECTED(CUSTOMERS);
customerranked<=MAX(customerranked));CUSTOMERS[Customer Number]<>BLANK();
'Detail Sales Report'[Total Actual Revenue - Base]>0)
Obviously this is not correct. I hope you understand my problem. I need to refer a virtual column done with rankx in my measure running total
Sample data edited with measures: [here]: https://mega.nz/#!4t1y0AJI!XF2Vcejm6C50nnssQCS1bJEhnqIGiH1d-mIltVskRgE
While here is the PBIX file and it may work as you expected, but you should take a broom and sweep your model a little. To get it working just set up the relationship from District to Customer and then to Sales. Or even better, get rid of Districts table. You have that dimension in Customers table. I just slightly changed your measures to get it working but I would change them altogether. Probably you do not need to use FILTER function.
#RUNNINGTOTAL =
CALCULATE (
SUM ( 'Sales'[Revenue] ),
FILTER (
ALLSELECTED ( Customers ),
Customers[DAX RANK]
<= MAX ( Customers[DAX RANK] )
),
'Sales'[Revenue] > 0
)
Anyway I would start it from scratch.
Why do you have three tables? What is the purpose of table Districts. You can use the Districts form table Customers to slice Sales.
If you really do not accept corrected invoices and negative sales (ask yourself why), build a measure like that:
[Sales] =
CALCULATE (
SUM ( FactTable[Sales] ),
FactTable[Sales] > 0
)
And then refer to it in other measures. Check these posts to see differences of filtering:
DAX Calculate function with and without FILTER
Difference between CALCULATE(m, x=red) vs CALCULATE(m, KEEPFILTERS(x=red))
You may think of building a bridge table, between Customers and Sales, which will contain unique CustomerID of both tables. Dictionaries are updated with lag.
bridge =
DISTINCT (
UNION (
DISTINCT ( Sales[CustomerID] ),
DISTINCT ( Customers[CustomerID] )
)
)
Give it a shot: https://www.daxformatter.com/
It is indeed possible, and encouraged to define measures that calculates ranks and cumulative totals on the fly.
However, there are some visualization issues. It looks not possible to use a measure for x axis with "Line and clustered column chart". So it would not be possible to use the Rank measure for x axis. You may put Customer Number to x axis instead, however the chart will look badly with a categorical x axis. It will not fit in the screen and will require a long scroll to reach the right end. Practically, this will hardly work as a pareto chart.
On the basis of this observation, I suggest to use R / Python visual if possible. Here is an example with R visual.
library(dplyr)
library(ggplot2)
totalSales <- sum(dataset$SalesAmount)
dataset <- dataset %>%
arrange(desc(SalesAmount)) %>%
mutate(
CumulativeSales = cumsum(SalesAmount),
Rank = order(SalesAmount, decreasing = TRUE)
)
p <- ggplot(dataset, aes(x = Rank, y = SalesAmount)) +
geom_bar(stat = "identity", width = 1, fill = "#01b8aa")
ymax <- layer_scales(p)$y$range$range[2]
p <- p + geom_line(aes(y = CumulativeSales / totalSales * ymax),
size = 1, color = "#fd625e") +
scale_y_continuous(sec.axis = sec_axis(~ . * totalSales / ymax)) +
theme_bw()
p

Select row to display in Shiny data table with selectInput

I'm new to figuring out reactivity in shiny. I want to use selectInput to choose the name of a row and have the table display just that row and then several columns.
For example, if my rows are people ("Anna","Tim","Larry") and my columns are variables ("A","B","C") I want the selectInput to show "Anna" and the data table to display variables A,B, and C for only Anna.
I'm stuck on how to do this.
ui <- shinyUI(
fluidPage(
fluidRow(
column(2, selectInput("name", "Select a Name:",
c("Anna"= "smith.anna",
"Tim" = "miller.tim"))),
column(6, "People Table", tableOutput("mytable")
))))
server <- function(input, output) {
output$mytable <- renderTable({
mydataset[mydataset, input$name]})
}
I'm pretty sure it's my server functionality that's messed up, but all tips are helpful! Thanks!
See my comment:
mydataset <- data.frame(A = 1:3, B = 4:6, C = 7:9)
row.names(mydataset) <- c("smith.anna", "miller.tim", "page.larry")
ui <- shinyUI(
fluidPage(
fluidRow(
column(2, selectInput("name", "Select a Name:",
c("Anna"= "smith.anna",
"Tim" = "miller.tim"))),
column(6, "People Table", tableOutput("mytable")
))))
server <- function(input, output) {
output$mytable <- renderTable({
mydataset[input$name, ]
})
}
shinyApp(ui, server)

Plotting log odds against mid-point of category

I have a binary outcome variable (disease) and a continuous independent variable (age). There's also a cluster variable clustvar. Logistic regression assumes that the log odds is linear with respect to the continuous variable. To visualize this, I can categorize age as (for example, 0 to <5, 5 to <15, 15 to <30, 30 to <50 and 50+) and then plot the log odds against the category number using:
logistic disease i.agecat, vce(cluster clustvar)
margins agecat, predict(xb)
marginsplot
However, since the categories are not equal width, it would be better to plot the log odds against the mid-point of the categories. Is there any way that I can manually define that the values plotted on the x-axis by marginsplot should be 2.5, 10, 22.5, 40 and (slightly arbitrarily) 60, and have the points spaced appropriately?
If anyone is interested, I achieved the required graph as follows:
Recategorised age variable slightly differently using (integer) labels that represent the mid-point of the category:
gen agecat = .
replace agecat = 3 if age<6
replace agecat = 11 if age>=6 & age<16
replace agecat = 23 if age>=16 & age<30
replace agecat = 40 if age>=30 & age<50
replace agecat = 60 if age>=50 & age<.
For labelling purposes, created a label:
label define agecat 3 "Less than 5y" 11 "10 to 15y" 23 "15 to <30y" 40 "30 to <50y" 60 "Over 50 years"
label values agecat
Ran logistic regression as above:
logistic disease i.agecat, vce(cluster clustvar)
Used margins and plot using marginsplot:
margins agecat, predict(xb)
marginsplot

Customizing week number in R shiny

I am trying to build a shiny application where the output will say "The current week is x" where x is the week number. The problem in this case is my year starts on 3/30/2014 and I have defined a week to be from Sunday to Saturday which I am unable code properly resulting in erroneous output. I am attaching the code below. Any help will be greatly appreciated.
ui.R
library(shiny)
shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
dateInput('Start_Date',label = "Choose Date",value = Sys.Date())
),
mainPanel(
textOutput("text1")
),
)
))
server.R
library(shiny)
shinyServer(function(input, output) {
output$text1<-renderText({
paste("The current week is",ceiling(abs(difftime(as.Date("3/30/2014","%m/%d/%y"),as.Date(input$Start_Date),by="weeks"))/7))
})
})
I think you had small problem with formatting. I have added the start the day from which the year start too (so if you want your count to start from Sunday you can specify) so you can change it if you want.
rm(list = ls())
library(shiny)
ui = fluidPage(
sidebarLayout(
sidebarPanel(
dateInput('Year_starts',label = "Count From",value = as.Date("2014/03/30")),
dateInput('Start_Date',label = "Choose Date",value = Sys.Date())
),
mainPanel(
textOutput("text1")
),
)
)
server = function(input, output) {
output$text1<-renderText({
dates <- seq(input$Year_starts, as.Date(input$Start_Date), by = "weeks")
length(dates)-1
})
}
runApp(list(ui = ui, server = server))