shiny how apply different regression model - r

I would like to chose one of regression models from a selection of different kind of models and, then, apply it to a subset. But I've difficult to understand how I can paste the function in server.R
Here there is a part of code in ui.R
h3("Model Prediction"),
selectInput("regression", "Select Model:",
list("y~x",
"y~x^2")
In server.R I've written this code
dati<- as.data.frame( read.csv(file='file.csv', header=TRUE, sep=";", dec=","))
mydata <- reactive({
(pdata=subset(dati,index==input$proj))
})
shinyServer(function(input, output) {
#Simple plot
output$testPlot = renderPlot({
pdata=subset(dati,index==input$proj)
plot(pdata$gg, pdata$y )
})
###my data
mydata <- reactive({
(pdata=subset(dati,index==input$proj))
})
runRegression <- reactive({
lm(as.formula(paste(input$dependent," ~ ",paste(input$independent,collapse="+"))),data=dat)
})
})

You can try to use sprintf for it
like
selectInput("regression", "Select Model:",
list("y~x"="%s",
"y~x^2"="%s^2"))
as.formula(paste(input$dependent," ~ ",paste(sprintf(fmt = input$regression,input$independent),collapse="+")))

Related

RShiny regression with dynamic input

I am trying to build a linear regression that allows the user to select the dependent variable while independent variable are given with the lm() function. I currently get this errors message :
Can anyone help me, thank you for your time. Below is the code:
Warning: Error in [[: object of type 'closure' is not subsettable
(The part giving the error is the regression part), for the dataset there seems to be no problem, I can View the table used in the regression and it is fine. (input$property_name also work fine on it's own)
I deleted most of the code which I think was not relevant to make it easier to read
Ui
fluidPage(
fluidRow(
box(title="Filter Settings",status="primary",solidHeader=TRUE,collapsible=FALSE,width=2,style="height:120vh",
selectInput(inputId=ns("property_name"),label="Property to predict",choices=NULL,multiple=FALSE),
),
box(title="Predictive analysis",status="primary",solidHeader=TRUE,collapsible=FALSE,width=10,style="height:100vh",
withSpinner(
tabsetPanel(type = "tabs",
tabPanel("Teste",verbatimTextOutput(ns("Teste_output"))),
tabPanel("teste",verbatimTextOutput(ns("teste_output")))
)
)
)
)
)
Server
offlinePredictiveAnalysisServer <- function(input,output,session) {
values <- reactiveValues()
# Dynamically update the product code selection UI
observe({
product_selection <- unique(getSampleHeaderData()[,c("product_code","product_description")])
updateSelectInput(session,inputId="product_code",choices=sort(setNames(product_selection$product_code,product_selection$product_description)))
})
# Dynamically update the property selection UI
observe({
updateSelectInput(session,inputId="property_name",choices=sort(unique(getSamplePropertyData()$property_name)))
})
observeEvent(input$update,{
# Here I Get the batch offline property data in line with the selection parameters from de UI part( I deleted most of the parameters no relevant)
set.seed(123)
# 75% of the sample size
smp_size <- floor(0.70 * nrow(Ref_batch_offline_data))
# set the seed to make your partition reproducible
set.seed(123)
train_ind <- sample(seq_len(nrow(Ref_batch_offline_data)), size = smp_size)
train.data <- Ref_batch_offline_data[train_ind, ]
test.data <- Ref_batch_offline_data[-train_ind, ]
formula <- reactive({
paste0(input$property_name, "~", Glutamate) %>% as.formula()
})
# dummy model using reactive formula
model <- reactive({
lm(formula = formula(), data = train.data)
})
values[["df"]] <-model
)
# Make predictions on the test data
#predictions <- predict(model,newdata=Pred_batch_offline_data)
#View(predictions)
#values[["dff"]] <- predictions
})
output$Teste_output= renderPrint({
model<-values[["df"]]
summary(model)
})
output$teste_output= renderTable({
predictions <-values[["dff"]]
head(predictions)
})
}
Not 100% clear without having the data and all objects. Assuming Glutamate is a variable containing a string (so that this produces a valid formula) this could work with values[["df"]] <- model().
Since all the calculations already happen inside a reactive environment (observeEvent), this section
formula <- reactive({
paste0(input$property_name, "~", Glutamate) %>% as.formula()
})
# dummy model using reactive formula
model <- reactive({
lm(formula = formula(), data = train.data)
})
values[["df"]] <-model() #brackets added
can be simplified to
formula <- as.formula(paste0(input$property_name, "~", Glutamate))
model <- lm(formula, data = train.data)
values[["df"]] <- model
Here is a minimal demo for this on the iris dataset:
library(shiny)
ui <- fluidPage(
titlePanel("iris regression"),
sidebarLayout(
sidebarPanel(
selectInput("target", "regression target",
choices = c("Petal.Width", "Petal.Length"))
),
mainPanel(
plotOutput("summaryPlot")
)
)
)
server <- function(input, output) {
values <- reactiveValues()
observeEvent(input$target,{
formula <- as.formula(paste0(input$target, "~ ."))
model <- lm(formula, data = iris)
values[["model"]] <- model
})
output$summaryPlot <- renderPlot({
plot(values[["model"]])
})
}
shinyApp(ui = ui, server = server)

R Shiny - create a table and populate it with the data frame data selected in drop down menu

I am continuing my struggles through R & R Shiny and have a question. I have a list of data frames. I want to use the names of the data frames from this list, to populate selectInput, and based on the selection of the data frame, I want to be able to view selected data frame, and see the statistics of its columns.
So far I have found this code
shinyServer(function(input, output) {
reactive_df <- reactive({
if(input$x=="All")
return df
else
return(select(df, starts_with(input$x)))
}
output$x <- renderDataTable(reactive_df())
}
But it does not do exactly what I want. Does anyone know how to create the table and the summaries?
You could have a look at mastering shiny:
ui <- fluidPage(
selectInput("dataset", label = "Dataset", choices = ls("package:datasets")),
verbatimTextOutput("summary"),
tableOutput("table")
)
server <- function(input, output, session) {
output$summary <- renderPrint({
dataset <- get(input$dataset, "package:datasets")
summary(dataset)
})
output$table <- renderTable({
dataset <- get(input$dataset, "package:datasets")
dataset
})
}
shinyApp(ui=ui,server=server)
If you have your own list of dataset, you can use [[...]] instead of get:
datasetlist <- list(iris = iris, mtcars = mtcars)
data <- datasetlist[[input$datasetname]]
for example if input$datasetname=='iris', you can check that this will assign iris to data for further processing:
data <- datasetlist[["iris"]]
data
Another option is :
data <- eval(parse(text=input$datasetname))

How to view the model result in shiny?

I want to develop generalised regression model which would allow user to select the variables of their choice and see the result. I do not seem to see the result.
library(shiny)
library(dplyr)
library(caret)
data(mtcars)
UI <- fluidPage(
titlePanel("MTCARS"),
selectInput("response","y",
names(mtcars)),
selectInput("Columns","Columns",
names(mtcars), multiple = TRUE),
actionButton('btn_train',label = 'Calibrate Model',
icon = icon('cogs'),#'bullseye','rocket'
class='btn-danger fa-lg',
width='100%'),
dataTableOutput("dfStr")
)
Server <- function(input, output) {
x <- reactive({as.character(input$Columns)})
y <- reactive({as.character(input$response)})
framework <- reactive({train(reformulate(x(), y()), data = mtcars, method='glm', maxit=500, trace=F)})
modeloutput <- reactive({
summary(framework())
})
observeEvent(input$btn_train,
output$dfStr <- renderPrint({
str(modeloutput())
}))
}
shinyApp(UI, Server)
It seems that the problem is that you are using dataTableOutput("dfStr") instead of verbatimTextOutput("dfStr").
Also the the Calibrate Model button is doing nothing since you are using reactive variables to build the model.

How can I change the input dataset in Shiny R?

I would like to select some rows of a dataset given an input defined by the user. In this case I would like to run different classification trees depending on the different positions in the field. I have a selectInput() in Shiny R which expands a menu where you can select for which field position you want to run the tree. However, for the moment it only runs for all the positions but not for each one individually. I'd appreciate some help on how to switch between datasets depending on user selection.
server.R
library(shiny)
library("rpart")
library("party")
library("partykit")
setwd("~/UNIVERSIDAD/EUR/Block 2/Machine Learning/Shiny App Both")
dat <- read.csv("Voetballers.csv")
dat <- dat[,3:20]
shinyServer(function(input, output, session) {
observe({
if(input$position=="All"){
dat <- dat
}
else if(input$position=="Forward"){
dat <- dat[dat$Position=="Forward",]
}
else if(input$position=="Midfielder"){
dat <- dat[dat$Position=="Midfielder",]
}
else if(input$position=="Defender"){
dat <- dat[dat$Position=="Defender",]
}
else if(input$position=="Goalkeeper"){
dat <- dat[dat$Position=="Goalkeeper",]
}
})
output$independent <- renderUI({
checkboxGroupInput("independent", "Independent Variables:",names(dat)[!names(dat) %in% input$dependent],names(dat)[!names(dat) %in% input$dependent])
})
runRegression <- reactive({
ctree(as.formula(paste(input$dependent," ~ ",paste(input$independent,collapse="+"))),data=dat)
})
runRegression2 <- reactive({
rpart(as.formula(paste(input$dependent," ~ ",paste(input$independent,collapse="+"))),data=dat)
})
output$plot1 <- renderPlot({
plot(runRegression())})
output$plot2 <- renderPlot({
plot(as.party(runRegression2()))})
})

Possible to pass a model to output in a shiny app?

I would like to select a feature and model (from sidebar dropdown menu's) and be able to pass the model to a specific output where I print the summary of the model and show how well the model fits graphically. I currently have a reactive function in server.R that checks which input$model is selected, then fits the model and returns it. When I try to call this reactive function from output$evaluation I get errors. I'm not sure how to do this.
# server.R
#...
fitter <- reactive({
df_clean <- dataset() # another reactive function that selects the dataset to be used
rownames(df_clean) <- df_clean$timestamp
df_clean$timestamp <- NULL
if (input$Model == 'Linear'){
fit <- lm(input$Response ~., data=df_clean)
}
#... more if statements checking for other model types
return(fit)
})
# Model Evaluation
output$Evaluation <- renderPrint({
summary(fitter())
})
You can convert the string in your lm call to a formula, using as.formula.
library(shiny)
shinyApp(
shinyUI(
fluidPage(
inputPanel(
selectInput("Model", "Model:", choices=c("Linear", "Other")),
selectInput("Response", "Response:", choices=c("mpg", "disp"))
),
tableOutput("Evaluation")
)
),
shinyServer(function(input, output, session) {
fitter <- reactive({
df_clean <- mtcars
if (input$Model == 'Linear'){
fit <- lm(as.formula(paste(input$Response, "~.")), data=df_clean)
}
return(fit)
})
output$Evaluation <- renderTable({
summary(fitter())
})
})
)

Resources