Argument improper in shiny ggplot - r

I want to create a shiny app that plots a graph of the various data inside a table. I have created the shiny app which
Tells the user to select a file to plot
Loads the data file into a Data database
Asks the user which column to plot
Inserts various data into respective datframes
Then plots the respective selected column
The code is as follows
library(shiny)
library(ggplot2)
ui <- fluidPage(
titlePanel("Creating a database"),
sidebarLayout(
sidebarPanel(
textInput("name", "Company Name"),
numericInput("income", "Income", value = 1),
numericInput("expenditure", "Expenditure", value = 1),
dateInput("date", h3("Date input"),value = Sys.Date() ,min = "0000-01-01",
max = Sys.Date(), format = "dd/mm/yy"),
actionButton("Action", "Submit"),#Submit Button
actionButton("new", "New")),
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("Table", tableOutput("table")),
tabPanel("Download",
textInput("filename", "Enter Filename for download"), #filename
helpText(strong("Warning: Append if want to update existing data.")),
downloadButton('downloadData', 'Download'), #Button to save the file
downloadButton('Appenddata', 'Append')),#Button to update a file )
tabPanel("Plot",
actionButton("filechoose", "Choose File"),
br(),
selectInput("toplot", "To Plot", choices = c("Income" = "inc",
"Expenditure" = "exp",
"Gross Profit" = "gprofit",
"Net Profit" = "nprofit"
)),
actionButton("plotit", "PLOT"),
plotOutput("Plot"))
)
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output){
#Global variable to save the data
Data <- data.frame()
Results <- reactive(data.frame(input$name, input$income, input$expenditure,
as.character(input$date),
as.character(Sys.Date())))
#To append the row and display in the table when the submit button is clicked
observeEvent(input$Action,{
Data <<- rbind(Data,Results()) #Append the row in the dataframe
output$table <- renderTable(Data) #Display the output in the table
})
observeEvent(input$new, {
Data <<- NULL
output$table <- renderTable(Data)
})
observeEvent(input$filechoose, {
Data <<- read.csv(file.choose()) #Choose file to plot
inc <- as.numeric(Data[ ,2])
exp <- as.numeric(Data[ ,3])
date <- Data[,4]
gprofit <- exp - inc
nprofit <- (exp - inc) * 0.06
output$table <- renderTable(Data) #Display the choosen file details
})
output$downloadData <- downloadHandler(
filename = function() {
paste(input$filename , ".csv", sep="")}, # Create the download file name
content = function(file) {
write.csv(Data, file,row.names = FALSE) # download data
})
output$Appenddata <- downloadHandler(
filename = function() {
paste(input$filename, ".csv", sep="")},
content = function(file) {
write.table( Data, file=file.choose(),append = T, sep=',',
row.names = FALSE, col.names = FALSE) # Append data in existing
})
observeEvent(input$plotit, {
bab <- input$toplot
output$Plot <- renderPlot("Plot",
ggplot()+ geom_bar(data = Data, aes(x= input$toplot,
y= date)))})
}
# Run the application
shinyApp(ui = ui, server = server)
but when i press the "plot" button, it gives the error
Error in *: non-numeric argument to binary operator`
Where i am wrong? Also i have used the as.numeric to convert the data into numeric so as to remove the error. Open for suggestions to change it also. Please Help. Thank You.
The data is like

Use switch case from switch() statement usage
or How to use the switch statement in R functions? to aid your choice option.
library(shiny)
library(ggplot2)
ui <- fluidPage(
titlePanel("Creating a database"),
sidebarLayout(
sidebarPanel(
textInput("name", "Company Name"),
numericInput("income", "Income", value = 1),
numericInput("expenditure", "Expenditure", value = 1),
dateInput("date", h3("Date input"),value = Sys.Date() ,min = "0000-01-01",
max = Sys.Date(), format = "dd/mm/yy"),
actionButton("Action", "Submit"),#Submit Button
actionButton("new", "New")),
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("Table", tableOutput("table")),
tabPanel("Download",
textInput("filename", "Enter Filename for download"), #filename
helpText(strong("Warning: Append if want to update existing data.")),
downloadButton('downloadData', 'Download'), #Button to save the file
downloadButton('Appenddata', 'Append')),#Button to update a file )
tabPanel("Plot",
actionButton("filechoose", "Choose File"),
br(),
selectInput("toplot", "To Plot", choices = c("Income" = "inc",
"Expenditure" = "exp",
"Gross Profit" = "gprofit",
"Net Profit" = "nprofit"
)),
actionButton("plotit", "PLOT"),
plotOutput("Plot")
)
)
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output){
#Global variable to save the data
Data <- data.frame()
Results <- reactive(data.frame(input$name, input$income, input$expenditure,
as.character(input$date),
as.character(Sys.Date())))
#To append the row and display in the table when the submit button is clicked
observeEvent(input$Action,{
Data <<- rbind(Data,Results()) #Append the row in the dataframe
output$table <- renderTable(Data) #Display the output in the table
})
observeEvent(input$new, {
Data <<- NULL
output$table <- renderTable(Data)
})
observeEvent(input$filechoose, {
Data <<- read.csv(file.choose()) #Choose file to plot
output$table <- renderTable(Data) #Display the choosen file details
})
output$downloadData <- downloadHandler(
filename = function() {
paste(input$filename , ".csv", sep="")}, # Create the download file name
content = function(file) {
write.csv(Data, file,row.names = FALSE) # download data
})
output$Appenddata <- downloadHandler(
filename = function() {
paste(input$filename, ".csv", sep="")},
content = function(file) {
write.table( Data, file=file.choose(),append = T, sep=',',
row.names = FALSE, col.names = FALSE) # Append data in existing
})
observeEvent(input$plotit, {
inc <- c(Data[ ,2])
exp <- c(Data[ ,3])
date <- c(Data[,4])
gprofit <- c(Data[ ,3]- Data[ ,2])
nprofit <- (exp - inc) * 0.06
y = input$toplot
switch(EXPR = y ,
inc = output$Plot <- renderPlot(ggplot(data = Data, aes(x= date, y= inc))+
geom_bar(stat = "identity",
fill = "blue")+xlab("Dates")+
ylab("Income")),
exp = output$Plot <- renderPlot(ggplot(data = Data, aes(x= date, y= exp))+
geom_bar(stat = "identity",
fill = "blue")+xlab("Dates")+
ylab("Expenditure")),
gprofit = output$Plot <- renderPlot(ggplot(data = Data, aes(x= date, y= gprofit))+
geom_bar(stat = "identity",
fill = "blue")+xlab("Dates")+
ylab("Gross Profit")),
nprofit = output$Plot <- renderPlot(ggplot(data = Data, aes(x= date, y= nprofit))+
geom_bar(stat = "identity",
fill = "blue")+xlab("Dates")+
ylab("Net Profit")))})
}
# Run the application
shinyApp(ui = ui, server = server)

Related

How to run code based on the condition of a selected checkbox in a shiny app?

I'm trying to implement a shiny app that contains some optional checkboxes. I would like to know how do I perform an analysis with a certain selection only if it is selected and, with that, the table with the analysis made from the selection also appears on the screen.
I would like the objects inside the rbind function (below) to be included only if they are selected in the checkboxes:
ameacadas <- rbind(ameacadas_BR,ameacadas_BR2, ameacadas_pa)
External files can be found at: https://github.com/igorcobelo/data_examples (The 'minati.csv' file is the input data).
My code is presented below:
# global
library(shiny)
library(tidyverse)
# ui
ui <- navbarPage(title = "Minati Flora.",
tabPanel(title = "Home",
br(),
hr(),
# Upload csv file
sidebarLayout(
sidebarPanel(
fileInput(
inputId = "csvFile",
label = "Upload",
accept = c(".csv")
),
checkboxInput('BR1','Federal1'),
checkboxInput('BR2','Federal2'),
checkboxInput('PA','ParĂ¡'),
downloadButton("download", "Download")
),
mainPanel(
tableOutput("modifiedData")
)
)
),
tabPanel(title = "About"),
inverse = T)
# server
server <- function(input, output) {
rawData <- eventReactive(input$csvFile, {
req(input$csvFile)
df <- read.csv(input$csvFile$datapath,sep=';',check.names = F,fileEncoding = "Latin1")
#read extern files
ameacadas_BR <- read.csv("ameacadas_BR.csv",sep=';',check.names = F,fileEncoding = "Latin1")
legis_BR <- "Portaria MMA N. 148/2022"
ameacadas_BR2 <- read.csv("ameacadas_BR2.csv",sep=';',check.names = F,fileEncoding = "Latin1")
legis_BR2 <- "Decreto Federal N. 5.975/2006"
ameacadas_pa <- read.csv("ameacadas_PA.csv",sep=';',check.names = F,fileEncoding = "Latin1")
legis_pa <- "Resolucao COEMA/PA N. 54/2007"
#Rbind all files selected
ameacadas <- rbind(ameacadas_BR,ameacadas_BR2, ameacadas_pa)
#General calculate
colnames(df)[1] <- "Especie" #coluna especies
ameacadas <- ameacadas %>%
group_by(Especie) %>%
mutate(Categoria_Ameaca = toString(Categoria_Ameaca),
Legislacao = toString(Legislacao))
ameacadas <- ameacadas[!duplicated(ameacadas[,1]),]
arv_com_ameacadas <- df %>% left_join(ameacadas, by = "Especie")
})
output$modifiedData <- renderTable({rawData() })
output$download <- downloadHandler(
filename = function() {paste("Minati_Flora_", Sys.Date(), ".csv", sep = "")},
content = function(file){
write.csv(rawData(), file, row.names = FALSE)
}
)
}
# Run the application
shinyApp(ui = ui, server = server)

Problem with selectInput Inside a renderUI command. when I select a choice, the code runs normally but then it gives me again the original choices

Hi I would appreciate your help.
I have the attached code. I import an excel data file and read the data. I have a renderUi command which by selectInput, reads the names of the inserted table and plots the relative columns of the data table.
When I run the code and I select the ParameterName_time and ParameterName ( which are the x and y parts of the plot ) , I can see the plot for just half a second but then it dissapears and the choices are back in the original state.
It looks like it is working but can not store the result.
Maybe I need to use the updateselectInput command or it is something with the reactivity of hte inputs or the plot. please help !
# Define server function
server <- function(input,output,session) {[enter image description here][1]
Excel <- reactive({ # DATA IMPORT ------------------------------------------
inFile <- input$Excel
if (is.null(inFile)) { return(NULL) }
dataFile <- read_excel(inFile$datapath,sheet=1)
return(dataFile)
})
RV <- reactiveValues(Excel = data.frame())
output$Table_Of_Data = DT::renderDataTable({ # DATA TABLE ------------------------------------------
RV$Excel<-Excel()
},options = list(scrollX = TRUE))
# if (input$submitbutton_Show_Table>0){
# }
output$summary <- renderPrint({ # Summary of DATA TABLE ------------------------------------------
dataset <- Excel()
summary(dataset)
})
# RValsl <- reactive(input$NumberOfDates_L )
# RValsr<- reactive(input$NumberOfDates_R )
output$timeDataSetNumber <- renderUI({
fluidRow(
numericInput(inputId = "NumberOfDates_L", # INPUT PARAMETER
label = "Number Of Different Time Data Sets (Left Side):",
value = 1 ,
min = 1,
),
numericInput(inputId = "NumberOfDates_R", # INPUT PARAMETER
label = "Number Of Different Time Data Sets (Right Side):",
value = 1 ,
min = 1,
)
)
})
output$Plotoutput <- renderPlot({
n<-input$NumberOfDates_L
output$tabsets <- renderUI({
Panels <- lapply(1:n, function(number){
tabPanel(paste0("Set #", number),
fluidRow(
selectInput("ParameterName_time","Select the Date vector for this entry",names(RV$Excel),multiple = TRUE ),
selectInput("ParameterName", "Select the KPIs for this entry:", names(RV$Excel) ,multiple = TRUE ),
),
)
})
do.call(tabsetPanel,Panels)
})
#============
k<-input$NumberOfDates_R
output$tabsets_R <- renderUI({
Panels_R <- lapply(1:k, function(number){
tabPanel(paste0("Set #", number),
fluidRow(
selectInput("ParameterName_time_R","Select the Date vector for this entry",names(RV$Excel)),
selectInput("ParameterName_R", "Select the KPIs for this entry:",names(RV$Excel),multiple = TRUE),
),
)
})
do.call(tabsetPanel,Panels_R)
})
Excel<-RV$Excel ##########################################################
###############################
###################################################
# if (input$submitbutton>0){
source(file = "path................TimeVector.R")
TVmean=TimeVector(input$Starting_Date,input$Ending_Date,input$Time)[,1]
TV1=TimeVector(input$Starting_Date,input$Ending_Date,input$Time)[,2]
TV2=TimeVector(input$Starting_Date,input$Ending_Date,input$Time)[,3]
#====================================================
# Value<- Excel %>% select(c(input$ParameterName))
source(file = "C:/Users/AntoniosTriantos/OneDrive - ClearWELL Oilfield Solutions/Desktop/App/Scripts/ReducedParameter.R")
# Left Side of the plot
kpi_entries=length(input$ParameterName)
# kpi_Time_entries=length(input$ParameterName_time)
KPITable=c(TVmean)
for ( i in 1:kpi_entries){
# for ( j in 1:kpi_Time_entries){
AV_Prop_Value_reduced=ReducedParameter(input$ParameterName_time[1],input$ParameterName[i],Excel,TV1,TV2)
KPITable=(cbind.data.frame(KPITable,AV_Prop_Value_reduced ))
}
# }
# Right Side of the plot
if (length(input$ParameterName_R)>0){
kpi_entries_R=length(input$ParameterName_R)
KPITable_R=c(TVmean)
for ( i in 1:kpi_entries_R){
AV_Prop_Value_reduced_R=ReducedParameter(input$ParameterName_time_R[1],input$ParameterName_R[i],Excel,TV1,TV2)
KPITable_R=(cbind.data.frame(KPITable_R,AV_Prop_Value_reduced_R ))
}
}
#====================================================
source(file = "path................Plot.R")
Plot<-PlotFunction(TVmean,AV_Prop_Value_reduced,kpi_entries,KPITable,input$ParameterName_R,kpi_entries_R,KPITable_R)
# }
})
}
ui <- fluidPage(theme = shinytheme("cerulean"),
navbarPage(
# theme = "cerulean", # <--- To use a theme, uncomment this
"ClearKPI",
tabPanel("Navbar 1",
sidebarPanel(wellPanel(fileInput('Excel', 'Choose XLSX File',
accept=c('sheetName', 'header'), multiple=FALSE))),
# actionButton("submitbutton_Show_Table","Show table",class ="btn btn-primary"),
h1("Excel Data"),
DT::dataTableOutput("Table_Of_Data"), # SHOW DATA TABLE
# Output: Verbatim text for data summary ----
verbatimTextOutput("summary"),
headerPanel("KPI Entry Point") , # INPUT KPIs vs Dates PARAMETER
uiOutput("timeDataSetNumber") ,
mainPanel(h2("Left side of the plot - Input:"),
uiOutput("tabsets")),
mainPanel(h2("Right side of the plot - Input:"),
uiOutput("tabsets_R")),
headerPanel("Edit Plot") , # INPUT KPIs vs Dates PARAMETER
numericInput(inputId = "Time", # INPUT PARAMETER
label = "Number of Hours to round:",
value = 4),
dateInput(
inputId="Starting_Date" ,
label="Starting Date:",
value = "2022-02-08",
min = NULL,
max = NULL,
format = "yyyy-mm-dd",
startview = "year",
weekstart = 0,
language = "en",
width = NULL,
autoclose = TRUE,
datesdisabled = NULL,
daysofweekdisabled = NULL),
dateInput( # INPUT PARAMETER
inputId="Ending_Date" ,
label="Ending Date:",
value = "2022-06-27",
min = NULL,
max = NULL,
format = "yyyy-mm-dd",
startview = "year",
weekstart = 0,
language = "en",
width = NULL,
autoclose = TRUE,
datesdisabled = NULL,
daysofweekdisabled = NULL),
# actionButton("submitbutton","Submit",class ="btn btn-primary"),
mainPanel(h2("Plot:"),
plotOutput(outputId = "Plotoutput", width = 1250 , height = 800) # OUTPUT PARAMETER
), # mainPanel
)
)
)
rm(list = ls())
source(file = "path................UI.R")
source(file = "path................SERVER.R")
# Create Shiny object
shinyApp(ui = ui, server = server)
I found the answer.
You need to introduce the actionbuttons to stop the procedure for being reactive and then you need to introduce both selectInpout and UpdateSelectInput commands.
# Define server function
server <- function(input,output,session) {
Excel <- reactive({ # DATA IMPORT ------------------------------------------
inFile <- input$Excel
if (is.null(inFile)) { return(NULL) }
dataFile <- read_excel(inFile$datapath,sheet=1)
return(dataFile)
})
RV <- reactiveValues(Excel = data.frame())
output$Table_Of_Data = DT::renderDataTable({ # DATA TABLE ------------------------------------------
if((input$submitbutton_Show_Table %% 2) == 0){
RV$Excel<-Excel()
}
},options = list(dom='Bfrtip',buttons=list('copy','pdf','csv','excel','print')) , extensions='Buttons')
# if (input$submitbutton_Show_Table>0){
# }
output$summary <- renderPrint({ # Summary of DATA TABLE ------------------------------------------
if((input$submitbutton_Summary %% 2) == 0){
dataset <- Excel()
summary(dataset)
}
})
output$Plotoutput <- renderPlot({
Excel<-isolate(RV$Excel )
#==================
RValsl <- (input$NumberOfDates_L )
RValsr<- (input$NumberOfDates_R )
output$timeDataSetNumber <- renderUI({
fluidRow(
numericInput(inputId = "NumberOfDates_L", # INPUT PARAMETER
label = "Number Of Different Time Data Sets (Left Side):",
value = RValsl()) ,
numericInput(inputId = "NumberOfDates_R", # INPUT PARAMETER
label = "Number Of Different Time Data Sets (Right Side):",
value = RValsr())
)
})
#===========================
if ((input$submitbuttonENTERKPIS %% 2) == 0) {
n<-input$NumberOfDates_L
output$tabsets <- renderUI({
Panels <- lapply(1:n, function(number){
tabPanel(paste0("Set #", number),
fluidRow(
selectInput("ParameterName_time","Select the Date vector for this entry",names(RV$Excel) ),
selectInput("ParameterName", "Select the KPIs for this entry:", names(RV$Excel) ,multiple = TRUE ),
),
)
})
updateSelectInput(session, "ParameterName_time",
label ="Select the Date vector for this entry" ,
choices = names(RV$Excel) )
updateSelectInput(session, "ParameterName",
label ="Select the KPIs for this entry:" ,
choices = names(RV$Excel) )
do.call(tabsetPanel,Panels)
})
#============
k<-input$NumberOfDates_R
output$tabsets_R <- renderUI({
Panels_R <- lapply(1:k, function(number){
tabPanel(paste0("Set #", number),
fluidRow(
selectInput("ParameterName_time_R","Select the Date vector for this entry",names(RV$Excel)),
selectInput("ParameterName_R", "Select the KPIs for this entry:",names(RV$Excel),multiple = TRUE),
),
)
})
updateSelectInput(session, "ParameterName_time_R",
label ="Select the Date vector for this entry" ,
choices = names(RV$Excel) )
updateSelectInput(session, "ParameterName_R",
label ="Select the KPIs for this entry:" ,
choices = names(RV$Excel) )
do.call(tabsetPanel,Panels_R)
})
}
# Excel<-RV$Excel ##########################################################
###############################
###################################################
if ((input$submitbutton %% 2) == 0) {
source(file = "C:/Users/AntoniosTriantos/OneDrive - ClearWELL Oilfield Solutions/Desktop/App/Scripts/TimeVector.R")
TVmean=TimeVector(input$Starting_Date,input$Ending_Date,input$Time)[,1]
TV1=TimeVector(input$Starting_Date,input$Ending_Date,input$Time)[,2]
TV2=TimeVector(input$Starting_Date,input$Ending_Date,input$Time)[,3]
#====================================================
# Value<- Excel %>% select(c(input$ParameterName))
source(file = "C:/Users/AntoniosTriantos/OneDrive - ClearWELL Oilfield Solutions/Desktop/App/Scripts/ReducedParameter.R")
# Left Side of the plot
kpi_entries=length(input$ParameterName)
# kpi_Time_entries=length(input$ParameterName_time)
KPITable=c(TVmean)
for ( i in 1:kpi_entries){
# for ( j in 1:kpi_Time_entries){
AV_Prop_Value_reduced=ReducedParameter(input$ParameterName_time[1],input$ParameterName[i],Excel,TV1,TV2)
KPITable=(cbind.data.frame(KPITable,AV_Prop_Value_reduced ))
}
# }
# Right Side of the plot
if (length(input$ParameterName_R)>0){
kpi_entries_R=length(input$ParameterName_R)
KPITable_R=c(TVmean)
for ( i in 1:kpi_entries_R){
AV_Prop_Value_reduced_R=ReducedParameter(input$ParameterName_time_R[1],input$ParameterName_R[i],Excel,TV1,TV2)
KPITable_R=(cbind.data.frame(KPITable_R,AV_Prop_Value_reduced_R ))
}
}
#====================================================
source(file = "C:/Users/AntoniosTriantos/OneDrive - ClearWELL Oilfield Solutions/Desktop/App/Scripts/Plot.R")
Plot<-PlotFunction(TVmean,AV_Prop_Value_reduced,kpi_entries,KPITable,input$ParameterName_R,kpi_entries_R,KPITable_R)
}
})
}

adding filter to the shiny for regression model

I have a fully functioning shiny app for performing regression analysis, with summary(), tidy(), and augment().
However, I would like to add a filter selection in the shiny for the uploaded data.
My dataset is quite big and within the dataset, it is divided into 5 types, (so, type_1, type_2, type_3, etc). Right now I have to divide my dataset manually outside the shiny app to 5 different datasets so I can only run the regression for one specific type at a time.
It would be great to be able to choose and select the type within the shiny, without going through all this hassle.
Grateful for all your help.
library(shiny)
library(shinyWidgets)
library(DT)
library(dplyr)
library(nlme)
library(broom)
ui <- navbarPage("dd",
tabPanel("Reg",
sidebarPanel(
fileInput(
inputId = "filedata",
label = "Upload data. csv",
multiple = FALSE,
accept = c(".csv"),
buttonLabel = "Choosing ...",
placeholder = "No files selected yet"
),
uiOutput("xvariable"),
uiOutput("yvariable")
),
mainPanel(
DTOutput("tb1"),
fluidRow(
column(6, verbatimTextOutput('lmSummary')),
column(6,verbatimTextOutput("tid")),
column(6,verbatimTextOutput("aug"))
)
)
)
)
server <- function(input, output, session) {
data_1 <- reactive({
req(input$filedata)
inData <- input$filedata
if (is.null(inData)){ return(NULL) }
mydata <- read.csv(inData$datapath, header = TRUE, sep=",")
})
output$tb1 <- renderDT(head(data_1()))
output$xvariable <- renderUI({
req(data_1())
xa<-colnames(data_1())
pickerInput(inputId = 'xvar',
label = 'Select x-axis variable',
choices = c(xa[1:length(xa)]), selected=xa[2],
options = list(`style` = "btn-info"),
multiple = TRUE)
})
output$yvariable <- renderUI({
req(data_1())
ya<-colnames(data_1())
pickerInput(inputId = 'yvar',
label = 'Select y-axis variable',
choices = c(ya[1:length(ya)]), selected=ya[1],
options = list(`style` = "btn-info"),
multiple = FALSE)
})
lmModel <- reactive({
req(data_1(),input$xvar,input$yvar)
x <- as.numeric(data_1()[[as.name(input$xvar)]])
y <- as.numeric(data_1()[[as.name(input$yvar)]])
current_formula <- paste0(input$yvar, " ~ ", paste0(input$xvar, collapse = " + "))
current_formula <- as.formula(current_formula)
model <- lm(current_formula, data = data_1(), na.action=na.exclude)
return(model)
})
output$lmSummary <- renderPrint({
req(lmModel())
summary(lmModel())
})
output$tid <- renderPrint({
req(lmModel())
tidy(lmModel())
})
output$aug <- renderPrint({
req(lmModel())
augment(lmModel())
})
}
shinyApp(ui, server)
How the uploaded dataset could look like, for better explanation
data_set <- data.frame (Simulation_1 = c(1,2,3,4,5,6,7,8,9,10),
Simulation_2 = c(1,2,3,4,5,6,7,8,9,10),
Simulation_3 = c(1,2,3,4,5,6,7,8,9,10),
type = c("type_1", "type_2", "Type_5",
"type_1", "type_2", "Type_3",
"type_1", "type_2", "Type_1","Type_4")
)
Perhaps you are looking for this
library(shiny)
library(shinyWidgets)
library(DT)
library(dplyr)
library(nlme)
library(broom)
data_set <- data.frame (Simulation_1 = c(1,2,3,4,5,6,7,8,9,10),
Simulation_2 = c(1,2,3,4,5,6,7,8,9,10),
Simulation_3 = c(1,2,3,4,5,6,7,8,9,10),
type = c("type_1", "type_2", "Type_5",
"type_1", "type_2", "Type_3",
"type_1", "type_2", "Type_1","Type_4")
)
ui <- navbarPage("dd",
tabPanel("Reg",
sidebarPanel(
fileInput(
inputId = "filedata",
label = "Upload data. csv",
multiple = FALSE,
accept = c(".csv"),
buttonLabel = "Choosing ...",
placeholder = "No files selected yet"
),
uiOutput("col"),
uiOutput("type"),
uiOutput("xvariable"),
uiOutput("yvariable")
),
mainPanel(
DTOutput("tb1"),
fluidRow(
column(6, verbatimTextOutput('lmSummary')),
column(6,verbatimTextOutput("tid")),
column(6,verbatimTextOutput("aug"))
)
)
)
)
server <- function(input, output, session) {
data_0 <- reactive({
# req(input$filedata)
# inData <- input$filedata
# if (is.null(inData)){ return(NULL) }
# mydata <- read.csv(inData$datapath, header = TRUE, sep=",")
data_set
})
output$tb1 <- renderDT(head(data_1()))
output$col <- renderUI({
req(data_0())
selected = colnames(data_0())[length(colnames(data_0()))]
selectInput("mycol", "Choose column", choices = colnames(data_0()), selected = selected)
})
output$type <- renderUI({
req(data_0(),input$mycol)
selectInput("mytype", "Choose Type", choices = unique(data_0()[[input$mycol]]))
})
data_1 <- eventReactive(input$mytype, {
req(data_0(),input$mycol,input$mytype)
df <- data_0()
df$newvar <- df[[input$mycol]]
df %>% dplyr::filter(newvar %in% input$mytype) %>% dplyr::select(- c(newvar))
})
output$xvariable <- renderUI({
req(data_1())
xa<-colnames(data_1())
pickerInput(inputId = 'xvar',
label = 'Select x-axis variable',
choices = c(xa[1:length(xa)]), selected=xa[2],
options = list(`style` = "btn-info"),
multiple = TRUE)
})
output$yvariable <- renderUI({
req(data_1())
ya<-colnames(data_1())
pickerInput(inputId = 'yvar',
label = 'Select y-axis variable',
choices = c(ya[1:length(ya)]), selected=ya[1],
options = list(`style` = "btn-info"),
multiple = FALSE)
})
lmModel <- reactive({
req(data_1(),input$xvar,input$yvar)
x <- as.numeric(data_1()[[as.name(input$xvar)]])
y <- as.numeric(data_1()[[as.name(input$yvar)]])
current_formula <- paste0(input$yvar, " ~ ", paste0(input$xvar, collapse = " + "))
current_formula <- as.formula(current_formula)
model <- lm(current_formula, data = data_1(), na.action=na.exclude)
return(model)
})
output$lmSummary <- renderPrint({
req(lmModel())
summary(lmModel())
})
output$tid <- renderPrint({
req(lmModel())
tidy(lmModel())
})
output$aug <- renderPrint({
req(lmModel())
augment(lmModel())
})
}
shinyApp(ui, server)

Using autoplotly in shiny app with user selected columns

I am making a shiny app that allows the user to upload a CSV, then select the independent and dependent variables. Right now I am able to upload a file, select variables and run regression analysis. But, I am stuck at the step where I would pass the lm object to autoplot then making it interactive via autoplotly in a new tab. How can I create interactive regression plots via using user selected variables in a shiny app?
UI
ui = navbarPage(tabPanel("Regression Analysis",
dataTableOutput('mytable'),
sidebarLayout(
sidebarPanel(width=3, fileInput("file1", "Please choose a CSV file",
multiple = T,
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv")),
tags$hr(),
checkboxInput("header", "Header", TRUE),
radioButtons("sep", "Separator",
choices = c(Comma = ",",
Semicolon = ";",
Tab = "\t"),
selected = ","),
radioButtons("quote", "Quote",
choices = c(None = "",
"Double Quote" = '"',
"Single Quote" = "'"),
selected = '"'),
tags$hr(),
radioButtons("disp", "Display",
choices = c(Head = "head",
All = "all"),
selected = "head")
),
mainPanel(
tableOutput("contents"),
actionButton("choice", "Define Regression Variables"),
selectInput("independent", "Independent Variables:", choices = NULL, multiple = T),
uiOutput("dependent1"),
#tableOutput("Table_selected.col"),
verbatimTextOutput("regTab")
)
),
tabPanel("Plots",
icon = icon("chart-area"),
plotlyOutput(outputId = "RegPlots"))
)
Server
server = function(input, output, session) {
mydf <- reactive({
# input$file1 will be NULL initially. After the user selects
# and uploads a file, head of that data file by default,
# or all rows if selected, will be shown.
req(input$file1)
df = read.csv(input$file1$datapath,
header = input$header,
sep = input$sep,
quote = input$quote)
if(input$disp == "head") {
return(head(df))
}
else {
return(df)
}
})
output$contents = renderTable({
req(mydf())
mydf()
})
# Code for allowing the user to select the variables/columns of interest
info <- eventReactive(input$choice, {
req(mydf())
f <- mydf()
f
})
observeEvent(input$choice, { ## to update only when you click on the actionButton
req(info())
updateSelectInput(session,"independent", "Please Select independent Variable(s):", choices = names(info()) )
})
# output$Table_selected.col <- renderTable({
# input$choice
# req(info(),input$columns)
# f = info()
# f = subset(f, select = input$columns) #subsetting takes place here
# head(f)
# })
output$dependent1 = renderUI({
req(mydf(),input$independent)
radioButtons("dependent1", "Select a dependent Variable:",choices=names(mydf())[!names(mydf()) %in% input$independent])
})
### need to build your formuila correctly; It will work with multiple independent variables
### model <- reactive({lm(reformulate(input$IndVar, input$DepVar), data = RegData)})
runRegression <- reactive({
req(mydf(),input$independent,input$dependent1)
a = lm(reformulate(input$independent, input$dependent1), data=mydf())
a
# multinom(reformulate(input$independent, input$dependent1), data=mydf()) ### mulitnomial from nnet package
})
output$regTab = renderPrint({
req(runRegression())
if(!is.null(input$independent)){
summary(runRegression())
} else {
print(data.frame(Warning="Please select Model Parameters."))
}
})
}
output$RegPlots = renderPlotly({
req(runRegression())
# Plot the residuals
lm.plot.rsd = autoplot(a, label.size = 3, which = 1) +
theme_bw()
autoplotly(lm.plot.rsd +
ggplot2::ggtitle("Residuals vs Fitted"))
})
shinyApp(ui, server)
Error
Error in : Objects of type function not supported by autoplot.
Try this
output$RegPlots = renderPlot({
req(runRegression())
# Plot the residuals
a = runRegression()
ggplot(a, aes(x = .fitted, y = .resid)) +
geom_point() +
geom_smooth(method = loess, formula = y ~ x) +
labs(title="Residuals vs Fitted")
})
You can try other plots if you want.

Dynamically Generate Plots in Conditional Tabs using renderUI in Shiny

I need some help creating dynamic plots that go inside dynamic tabs. Here's the situation ... I have a data file that contains digital marketing data. The file has the following pieces of information: Campaign Name, Channel Name, Page Views, and Visits. Campaign Names are unique and roll up to one of four different marketing channels. This will change in the future depending on the data I feed it (for example, I may have six marketing channels in the next file I use), but this will do for troubleshooting purposes. I want to dynamically create tabs and output for each marketing channel in the file. I have been able to figure out how to create the tabs, but I'm having a hard time figuring out how to create other types of output (like a plot) to go with each tab.
The tabs were created using renderUI in the following code in the server file:
output$mytabs = renderUI({
if(is.null(rawData())){return ()}
channels = unique(rawData()$Channel)
myTabs = lapply(channels, tabPanel)
do.call(tabsetPanel, myTabs)
})
output$scatterPlot <- renderUI({
if(is.null(rawData())){return()}
createPlots()
myData = rawData()
channels = unique(myData$Channel)
plot_output_list <- lapply(seq_along(channels), function(i) {
plotname <- paste("plot", i, sep="")
plotOutput(plotname)
})
do.call(tagList, plot_output_list)
})
createPlots <- reactive ({
myData = rawData()
channels = unique(myData$Channel)
for (i in seq_along(channels)) {
local({
my_i <- i
plotname <- paste("plot", my_i, sep="")
tempRows = which(myData$Channel==channels[i])
output[[plotname]] <- renderPlot({
plot(x = myData$Spend[tempRows], y = myData$Return[tempRows])
})
})
}
})
These were then referenced in the ui file as follows:
mainPanel(
tabsetPanel(
tabPanel("Data Summary", uiOutput("dataSummary")),
tabPanel("Parameters & Model Fit",
uiOutput('mytabs'),
uiOutput('scatterPlot')),
tabPanel("Budget & Spend Summary"),
tabPanel("Testing", plotOutput('plot5'))
)
)
Ultimately, I'd like to plot Page Views vs Visits for each Marketing Channel on the corresponding marketing channel tab. At the moment, all four plots are showing up in each of marketing channel tab. In my global file, I've created two functions -- one function plots one channel at a time and another function that plots all the channels and saves each one as separate elements within a list. I'm not sure which one of these will end up being useful, if either.
I'm certain that I'm not understanding how to set 'myTabs' or I'm referencing it incorrectly from the ui. Even with this snippet of the code, someone here might be able to quickly spot the error and recommend a fix, but I am happy to provide the rest of my code if that would be helpful.
Thanks!
Jess
EDIT: For Reference, here is all of my code. Just changed the dir object to be the directory you want to work in.
library(shiny)
dir = ""
setwd(dir)
#######################
### Generate Data ###
#######################
channels = c("Affiliate","Email","Media","SEO")
nObs = c(round(runif(1,100,200)))
pageViews = runif(nObs*length(channels),50,500)
visits = runif(nObs*length(channels),10,100)
campaignNames = unlist(lapply(channels, FUN = function(x) paste(x,seq(from=1,to=nObs,by=1),sep="")))
channelNames = rep(channels,nObs)
myData = data.frame(Campaign = campaignNames, Channel = channelNames, Return = pageViews, Spend = visits)
write.table(myData,file="myTestData.csv",sep=",",col.names=TRUE,row.names=FALSE)
########################
### Global Functions #
########################
summarizeData = function(myDat){
summaryData = summarize(group_by(myDat,Channel), 'Campaign Count' = length(Campaign), Return = sum(Return), Spend = sum(Spend))
return(summaryData)
}
### PLOT DATA AND MODEL FIT ###
plotSingle = function(myData, channelName){
p1 <- ggplot(myData[which(myData$Channel==channelName),], aes(x = Spend, y = Return)) +
geom_point(color="black") +
theme(panel.background = element_rect(fill = 'grey85'),
panel.grid.major = element_line(colour = "white"))
return(p1)
}
plotAll = function(myData){
channels = unique(myData$Channel)
plots <- list() # new empty list
for (i in 1:length(channels)) {
channelName = channels[i]
p1 = plotSingle(myData = myData, channelName = channelName)
plots[[i]] = p1
}
return(plots)
}
############
### UI ###
############
ui <- fluidPage(
headerPanel('Plot Testing'),
sidebarPanel(
h3(helpText("Data Input")),
fileInput(inputId = "rawDataInput", label = "Upload Data"),
h5(helpText("Select the file parameters below")),
checkboxInput(inputId = 'header', label = 'Header', value = TRUE),
checkboxInput(inputId = "stringAsFactors", "stringAsFactors", FALSE),
br(),
radioButtons(inputId = 'sep', label = 'Separator', choices = c(Comma=',',Semicolon=';',Tab='\t', Space=''), selected = ',')
),
mainPanel(
tabsetPanel(
tabPanel("Data Summary", uiOutput("dataSummary")),
tabPanel("Parameters & Model Fit",
uiOutput('mytabs'),
uiOutput('scatterPlot')),
tabPanel("Budget & Spend Summary"),
tabPanel("Testing", plotOutput('plot5'))
)
)
)
################
### Server ###
################
server = function(input, output) {
rawData <- reactive({
file1 <- input$rawDataInput
if(is.null(file1)){return()}
read.table(file=file1$datapath, sep=input$sep, header = input$header, stringsAsFactors = input$stringAsFactors)
})
# this reactive output contains the summary of the dataset and display the summary in table format
output$filedf <- renderTable({
if(is.null(rawData())){return ()}
input$rawDataInput
})
# this reactive output contains the summary of the dataset and display the summary in table format
output$sum <- renderTable({
if(is.null(rawData())){return ()}
summarizeData(rawData())
})
# This reactive output contains the dataset and display the dataset in table format
output$table <- renderTable({
if(is.null(rawData())){return ()}
rawData()
})
dataPlots = reactive({
channels = unique(rawData()$Channel)
plots = plotAll(rawData())
})
output$mytabs = renderUI({
if(is.null(rawData())){return ()}
channels = unique(rawData()$Channel)
createPlots()
plot_output_list <- lapply(seq_along(channels), function(i) {
plotname <- paste("plot", i, sep="")
plotOutput(plotname)
})
myTabs = lapply(channels, tabPanel)
do.call(tabsetPanel, myTabs)
})
createPlots <- reactive ({
myData = rawData()
channels = unique(myData$Channel)
for (i in seq_along(channels)) {
local({
my_i <- i
plotname <- paste("plot", my_i, sep="")
tempRows = which(myData$Channel==channels[i])
output[[plotname]] <- renderPlot({
plot(x = myData$Spend[tempRows], y = myData$Return[tempRows])
})
})
}
})
output$scatterPlot <- renderUI({
if(is.null(rawData())){return()}
createPlots()
myData = rawData()
channels = unique(myData$Channel)
plot_output_list <- lapply(seq_along(channels), function(i) {
plotname <- paste("plot", i, sep="")
plotOutput(plotname)
})
do.call(tagList, plot_output_list)
})
output$dataSummary <- renderUI({
if(is.null(rawData())){return()}
else
tabsetPanel(tabPanel("About file", tableOutput("filedf")),tabPanel("Data", tableOutput("table")),tabPanel("Summary", tableOutput("sum")))
})
output$plot5 = renderPlot({
if(is.null(rawData())){return ()}
myData = rawData()
channelName = "Affiliate"
p1 <- ggplot(myData[which(myData$Channel==channelName),], aes(x = Spend, y = Return)) +
geom_point(color="black") +
theme(panel.background = element_rect(fill = 'grey85'),
panel.grid.major = element_line(colour = "white"))
return(p1)
})
}
### Run App ###
shinyApp(ui = ui, server = server)
Your example isn't exactly minimal so i did some stripping away. First the data and helper functions
library(shiny)
library(ggplot2)
channels = c("Affiliate","Email","Media","SEO")
nObs = c(round(runif(1,100,200)))
myData = data.frame(
Campaign = unlist(lapply(channels, FUN = function(x) paste(x,seq(from=1,to=nObs,by=1),sep=""))),
Channel = rep(channels,nObs),
Return = runif(nObs*length(channels),50,500),
Spend = runif(nObs*length(channels),10,100)
)
plotSingle = function(myData, channelName){
ggplot(myData[which(myData$Channel==channelName),], aes(x = Spend, y = Return)) +
geom_point(color="black") +
theme(panel.background = element_rect(fill = 'grey85'),
panel.grid.major = element_line(colour = "white"))
}
Now the UI
ui <- fluidPage(
headerPanel('Plot Testing'),
mainPanel(
uiOutput('mytabs'),
plotOutput('scatterPlot')
)
)
Note that we only use one plotOutput here. What we will do is just change the plot it's showing based on the currently selected tab. Here's the server code
server = function(input, output) {
rawData <- reactive({
myData
})
output$mytabs = renderUI({
if(is.null(rawData())){return ()}
channels = unique(rawData()$Channel)
myTabs = unname(Map(tabPanel, channels))
do.call(tabsetPanel, c(myTabs, id="channeltab"))
})
output$scatterPlot <- renderPlot({
if(is.null(rawData()) | is.null(input$channeltab)){return ()}
plotSingle(rawData(), input$channeltab)
})
}
You see we set an id on the tabsetPanel we create. We can then use that as input to determine which panel is selected and show the correct plot. All run with
shinyApp(ui = ui, server = server)

Resources