Hey I am trying to build a shiny app for the purpose of calculating per cent chance of defaulting and I thought I fixed all my issues until I hit
Error in .getReactiveEnvironment()$currentContext() :
Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)
but whenever I try to build something reactive I get
Error in RET#get_where(newdata = newdata, mincriterion = mincriterion) :
object 'loanfilev3' not found
I've looked over stackoverflow and tutorials and none seem to really help
Here is my UI and Server code for the first error, if someone could please highlight my issue that would be greatly appreciated.
UI:
library(shiny)
shinyUI(fluidPage(
titlePanel("Tabsets"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Select the random distribution type ----
numericInput("loan_amnt",
"Loan Amount:",
value = 5000,
min = 0,
max = NA),
numericInput("int_rate",
"Interest Rate:",
value = 10.5,
min = 0,
max = NA),
selectInput("term",
"Loan Term:",
c("36 months" = " 36 months",
"60 months" = " 60 months")),
numericInput("installment",
"Installment:",
value = 100,
min = 0,
max = NA),
textInput("grade", "Grade:", "B"),
textInput("emp_length", "Employment Length:", "5 years"),
numericInput("annual_inc",
"Annual Income:",
value = 40000,
min = 0,
max = NA),
numericInput("dti",
"Debt to Income Ratio:",
value = 5.4,
min = NA,
max = NA),
textInput("sub_grade", "SubGrade:", "B2"),
textInput("verification_status", "Verification Status:", "Verified"),
textInput("home_ownership", "Home Ownership:", "RENT"),
radioButtons("pymnt_plan", "Payment Plan:",
c("Yes" = "y",
"No" = "n"))
),
# Main panel for displaying outputs ----
mainPanel(
# Output: Tabset w/ plot, summary, and table ----
tabsetPanel(type = "tabs",
tabPanel("Decision Tree", verbatimTextOutput("ct")),
tabPanel("Generlized Linear Model", verbatimTextOutput("dl")),
tabPanel("K-Nearest Neighbour", verbatimTextOutput("kn"))
)
)
)
)
)
Server:
library(shiny)
library(pscl)
library(ROCR)
library(plyr)
library(dplyr)
library(ggplot2)
library(pROC)
library(caret)
library(e1071)
library(RMySQL)
library(reshape2)
USER <- 'inft216'
PASSWORD <- 'rosemary'
HOST <- 'bruce3.dc.bond.edu.au'
DBNAME <- 'inft216'
db <- dbConnect(MySQL(), user = USER, password = PASSWORD, host = HOST, dbname = DBNAME)
loanfile <- dbGetQuery(db, statement = "select * from lendingClub;")
dbDisconnect(db)
library(party)
colnames(loanfile) = tolower(colnames(loanfile))
bad_indicators = c("Charged Off",
"Default",
"Does not meet the credit policy. Status:Charged Off",
"Default Receiver",
"Late (16-30 days)",
"Late (31-120 days)")
loanfile$default = ifelse(loanfile$loan_status %in% bad_indicators, 1,
ifelse(loanfile$loan_status=="", NA, 0))
loanfile$loan_status = as.factor(loanfile$default)
loanfilev2 = dplyr::select(.data = loanfile,loan_status,loan_amnt,int_rate,term,installment,grade,emp_length,annual_inc,dti,sub_grade,verification_status,home_ownership,pymnt_plan)
loanfilev2$grade = as.factor(loanfilev2$grade)
loanfilev2$sub_grade <- as.factor(loanfilev2$sub_grade)
loanfilev2$term <- as.factor(loanfilev2$term)
loanfilev2$emp_length <- as.factor(loanfilev2$emp_length)
loanfilev2$verification_status <- as.factor(loanfilev2$verification_status)
loanfilev2$home_ownership <- as.factor(loanfilev2$home_ownership)
loanfilev2$pymnt_plan <- as.factor(loanfilev2$pymnt_plan)
loanfilev2$loan_status <- as.factor(loanfilev2$loan_status)
loanfilev2$grade <- as.numeric(loanfilev2$grade)
loanfilev2$sub_grade <- as.numeric(loanfilev2$sub_grade)
loanfilev2$term <- as.numeric(loanfilev2$term)
loanfilev2$emp_length <- as.numeric(loanfilev2$emp_length)
loanfilev2$verification_status <- as.numeric(loanfilev2$verification_status)
loanfilev2 <- loanfilev2[complete.cases(loanfilev2),]
set.seed(69)
train_index <- sample(seq_len(nrow(loanfilev2)), size = 5000)
TrainData<- loanfilev2[train_index, ]
ct = ctree(loan_status ~ ., data = TrainData)
dl <- glm(formula = loan_status ~ .,data = loanfilev2, family = binomial)
kn <- train(form = loan_status ~.,data = TrainData, method = 'knn')
shinyServer(function(input, output) {
loan_status <- c(0)
loan_amnt <- input$loan_amnt
int_rate <- input$int_rate
term <- input$term
installment <- input$installment
grade <- input$grade
emp_length <- input$emp_length
annual_inc <- input$annual_inc
dti <- input$dti
sub_grade <- input$sub_grade
verification_status <- input$verification_status
home_ownership <- input$home_ownership
pymnt_plan <- input$pymnt_plan
temp2 <- cbind(loan_status, loan_amnt, int_rate, term, installment, grade, emp_length, annual_inc, dti, sub_grade, verification_status, home_ownership, pymnt_plan)
loanfilev3 = dplyr::select(.data = loanfile,loan_status,loan_amnt,int_rate,term,installment,grade,emp_length,annual_inc,dti,sub_grade,verification_status,home_ownership,pymnt_plan)
loanfilev3 = rbind(loanfilev3, temp2, deparse.level = 0)
loanfilev3$grade = as.factor(loanfilev3$grade)
loanfilev3$sub_grade <- as.factor(loanfilev3$sub_grade)
loanfilev3$term <- as.factor(loanfilev3$term)
loanfilev3$emp_length <- as.factor(loanfilev3$emp_length)
loanfilev3$verification_status <- as.factor(loanfilev3$verification_status)
loanfilev3$home_ownership <- as.factor(loanfilev3$home_ownership)
loanfilev3$pymnt_plan <- as.factor(loanfilev3$pymnt_plan)
loanfilev3$loan_status <- as.factor(loanfilev3$loan_status)
loanfilev3$grade <- as.numeric(loanfilev3$grade)
loanfilev3$sub_grade <- as.numeric(loanfilev3$sub_grade)
loanfilev3$term <- as.numeric(loanfilev2$term)
loanfilev3$emp_length <- as.numeric(loanfilev3$emp_length)
loanfilev3$verification_status <- as.numeric(loanfilev3$verification_status)
loanfilev3 <- loanfilev3[complete.cases(loanfilev3),]
prediction1 = c(predict(object = ct, newdata = loanfilev3[886508], type = "prob"))
output$ct <- renderPrint({
as.data.frame(prediction1)[2,]*100
})
})
All input bindings (input$whatever) need to be used in reactive context for example: inside reactive() or observe or renderXXX etc. In your case you are doing stuff like loan_amnt <- input$loan_amnt outside of reactive context and that's what the error is about. See my update below. I have added your prediction model to an eventReactive that is triggered by some action button input$predict.
# add this button somewhere in your ui.R -
actionButton("predict", "Predict!")
update to server.R -
shinyServer(function(input, output) {
prediction <- eventReactive(input$predict, {
loan_status <- c(0)
loan_amnt <- input$loan_amnt
int_rate <- input$int_rate
term <- input$term
installment <- input$installment
grade <- input$grade
emp_length <- input$emp_length
annual_inc <- input$annual_inc
dti <- input$dti
sub_grade <- input$sub_grade
verification_status <- input$verification_status
home_ownership <- input$home_ownership
pymnt_plan <- input$pymnt_plan
temp2 <- cbind(loan_status, loan_amnt, int_rate, term, installment, grade, emp_length, annual_inc, dti, sub_grade, verification_status, home_ownership, pymnt_plan)
loanfilev3 = dplyr::select(.data = loanfile,loan_status,loan_amnt,int_rate,term,installment,grade,emp_length,annual_inc,dti,sub_grade,verification_status,home_ownership,pymnt_plan)
loanfilev3 = rbind(loanfilev3, temp2, deparse.level = 0)
loanfilev3$grade = as.factor(loanfilev3$grade)
loanfilev3$sub_grade <- as.factor(loanfilev3$sub_grade)
loanfilev3$term <- as.factor(loanfilev3$term)
loanfilev3$emp_length <- as.factor(loanfilev3$emp_length)
loanfilev3$verification_status <- as.factor(loanfilev3$verification_status)
loanfilev3$home_ownership <- as.factor(loanfilev3$home_ownership)
loanfilev3$pymnt_plan <- as.factor(loanfilev3$pymnt_plan)
loanfilev3$loan_status <- as.factor(loanfilev3$loan_status)
loanfilev3$grade <- as.numeric(loanfilev3$grade)
loanfilev3$sub_grade <- as.numeric(loanfilev3$sub_grade)
loanfilev3$term <- as.numeric(loanfilev2$term)
loanfilev3$emp_length <- as.numeric(loanfilev3$emp_length)
loanfilev3$verification_status <- as.numeric(loanfilev3$verification_status)
loanfilev3 <- loanfilev3[complete.cases(loanfilev3),]
predict(object = ct, newdata = loanfilev3[886508], type = "prob"))
})
output$ct <- renderPrint({
as.data.frame(prediction())[2,]*100
})
})
Related
I tried to achieve when with a chosen split percentage, it returns the train set and then with a sampling method to resample train set and calculate its class freq and perc.
The error I got: object 'split.df' not found when I choose check box 'over'.
Should I use eventReactive or other syntax to achieve? The final return the table with either freq or perc should be dependent on 'split', 'sample' and dropdown 'freq' or 'perc'.
Here is portion that relates in ui:
sidebarLayout(
sidebarPanel(
h3("Train/test set"),
tags$br(),
selectInput(
"trainset",
"Select train component",
choices = list('freq'='freq', 'percentage'='perc'),
),
sliderInput(
"split",
label = "split percentage",
min = 0,
max = 1,
value = 0,
step = 0.1
),
h3("resampling train set"),
checkboxGroupInput('sample', label = "sampling method",
choices = list('original'='original','over'='over', 'under'='under', 'both'='both','ROSE'='ROSE'),
selected = list('original'='original'))
),
Here is a code relates for server:
split.df <- reactive({
index <- createDataPartition(df$class, p=input$split, list=FALSE)
Training_Data <- df[index,]
return(Training_Data)
})
train_set <- reactive({
if(input$sample == 'original')
Training_Data_class <- data.frame(class = split.df()$class)
return(Training_Data_class)
})
over_train_set <- reactive({
split.df <- split.df()
if(input$sample == 'over'){
over <- ovun.sample(class~., data = split.df, method = 'over')$data
Training_Data_class_over <- data.frame(class = over$class)
return(Training_Data_class_over)}
})
trainset_df <- reactive({
freq.df.train <- data.frame(table(train_set()))
colnames(freq.df.train) <- c('class', 'freq')
perc.df.train.=data.frame(prop.table(table(train_set()))*100)
colnames(perc.df.train) <- c('class','perc')
if(input$trainset == 'freq')
return(freq.df.train)
if(input$trainset == 'perc')
return(perc.df.train)
})
over_trainset_df <- reactive({
freq.df.train.over <- data.frame(table(over_train_set()))
colnames(freq.df.train.over) <- c('class', 'freq')
perc.df.train.over=data.frame(prop.table(table(over_train_set()))*100)
colnames(perc.df.train.over) <- c('class','perc')
if(input$trainset == 'freq')
return(freq.df.train.over)
if(input$trainset == 'perc')
return(perc.df.train.over)
})
output$trainsetdistr <- DT::renderDataTable({
if(input$sample == 'over'){
return(over_trainset_df())
}
if(input$sample == 'original'){
return(trainset_df())
}
}
)
I'm working on cancer data from TCGA.
Im new to shiny and creating web applications (learning it!!)
I'm working on a shiny tool to plot the volcanoplot using highcharter package.
sometimes I'm successfully able to plot the volcanoplot in the UI. but sometimes it fails to plot it and throws an error saying,
"An error has occurred!
could not find function "highchartOutput"
and one warning message is given for the error;
Listening on http://127.0.0.1:5335
Warning: Error in highchartOutput: could not find function "highchartOutput"
83: dots_list
82: div
81: tabPanel
I think there is some problem with the tabset panel.
is this error has anything to do with indentation? (wherever I adjust the brackets it works magically. not sure how it works for sometimes.)
I am attaching the UI and server files with this post.
code is attached for one type of comparison
UI file below:
library(shiny)
# Define UI for application
shinyUI(fluidPage(
# Application title
titlePanel("miR-Gyn-Explorer"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
## select the count matrix
selectInput("file", label = h3("Count Matrix"),
choices = list("Stage I - Normal" = list("TCGA-BRCA" = "Data/TCGA-BRCASI_NT.rda", "TCGA-UCEC" = "Data/TCGA-UCECSI_NT.rda"))),
## select the phenodata of samples
selectInput("phenofile", label = h3("Sample Phenodata"),
choices = list("Stage I - Normal" = list("TCGA-BRCA" = "Data/TCGA-BRCA_phenoSI_NT.rda", "TCGA-UCEC" = "Data/TCGA-UCEC_phenoSI_NT.rda"))),
submitButton("Update View")
),
# Show a plot of the generated distribution
mainPanel(
tabsetPanel(
tabPanel("DEmiRNA", DT::dataTableOutput("DEmiRNA"),
"Volcano-Plot", highchartOutput("volcanoPlot", height = "500px"))
#tabPanel("miRNA-Targets", DT::dataTableOutput('miRTarget'),
#plotOutput("GO"))
)
)
)
)
)
server file:
library(shiny)
library(R.utils)
##function to find the DEmiRNA by edgeR method
library(limma)
library(edgeR)
library(DT)
library(dplyr)
library(multiMiR)
library(miRBaseConverter)
library(ggplot2)
#library(ggrepel)
library(tidyverse)
library(highcharter)
library(org.Hs.eg.db)
library(clusterProfiler)
library(purrr)
gdcDEmiRNA <- function(counts, groups, comparison, filter=TRUE) {
## method = edgeR
dge = DGEList(counts = counts, samples = groups)
group <- factor(groups$group)
design <- model.matrix(~0+group)
colnames(design) <- levels(group)
contrast.matrix <- makeContrasts(contrasts=comparison,
levels=design)
keep = filterByExpr(dge,design)
dge <- dge[keep,,keep.lib.sizes = TRUE]
dge <- calcNormFactors(dge)
dge <- estimateDisp(dge, design)
fit <- glmFit(dge, design)
lrt <- glmLRT(fit, contrast=contrast.matrix)
DEGAll <- lrt$table
DEGAll$FDR <- p.adjust(DEGAll$PValue, method = 'fdr')
o <- order(DEGAll$FDR)
DEGAll <- DEGAll[o,]
return (DEGAll)
}
# Define server logic required to perform the DEmiRNA analysis
server <- function(input, output) {
d <- reactive({
#DEmiRNA calculation
file <- load(input$file)
phenofile <- load(input$phenofile)
if(file == "SI_NT"){
if(phenofile == "phenoSI_NT"){
DEmiRNA <- gdcDEmiRNA(counts = SI_NT, groups = phenoSI_NT,
comparison = 'StageI-Normal')
}
}
})
output$DEmiRNA <- DT::renderDataTable({
mir <- d()
#mir <- mir[mir$FDR < input$FDR,]
})
output$volcanoPlot <- renderHighchart({
x <- d()
x$mirna <- rownames(x)
x$sig <- ifelse(x$PValue < 0.05 & abs(x$logFC) > 0.57, "DEmiRNA", "Not Regulated")
hc <- highchart() %>%
hc_add_series(x, "scatter", hcaes(logFC, -log10(PValue), group = sig, value = mirna),
color = c('rgba(67, 67, 72, 0.6)', 'rgba(124, 181, 236, 0.6)'),
enableMouseTracking = c(TRUE, TRUE),
showInLegend = TRUE, marker = list(radius = 4)) %>%
hc_tooltip(pointFormat = "{point.value}", headerFormat = "") %>%
hc_xAxis(title = list(text = "Log fold change"), gridLineWidth = 1,
tickLength = 0, startOnTick = "true", endOnTick = "true", min = -6, max = 6) %>%
hc_yAxis(title = list(text = "-Log10(p-value)")) %>%
hc_chart(zoomType = "xy", width=700) %>%
hc_exporting(enabled = TRUE, filename = "volcano")
hc
})
}
any comment and help from you guys is appreciated
Thank you in advance!
-Ankita
I'm currently working on an Rshiny webapp to use for some simple classification. Currently, I've been working on creating a table that contains the CCR and MCR of both the CART and LDA methods on the data. My aim is then to highlight the column of the MCR and CCR of the best method (the method with the highest CCR... or lowest MCR). I have ran the code and viewed that it works correctly using the Viewer Pane. However, when I load the app, I obtain the error 'data' must be 2-dimensional (e.g. data frame or matrix).
Here is my code:
data <- read.csv("Fatality-task2.csv")
data$Rate <- as.factor(data$Rate)
library(shiny)
library(dplyr)
library(ggplot2)
library(markdown)
library(gtsummary)
library(ggdendro)
library(factoextra)
library(mclust)
library(cluster)
library(rpart)
library(rpart.plot)
library(DT)
#library(MASS)
glimpse(data)
#################################################################
ui <- fluidPage(
navbarPage("",
tabPanel("Data Exploration",
sidebarLayout(
sidebarPanel(
selectInput("variable",
"Variable",
colnames(data)),
selectInput("rate",
"Rate",
levels(data$Rate))
),
mainPanel(
tableOutput("table"),
plotOutput("plot")
)
)
),
tabPanel("Classification tools",
sidebarLayout(
sidebarPanel(
sliderInput("train.prop",
"Training data proportion",
min = 0.4,
max = 0.8,
step = 0.1,
value = 0.6),
radioButtons("prune",
"Pruning option",
choices = c("view pruned tree",
"view unpruned tree"))
),
mainPanel(
DTOutput("table2"),
plotOutput("plot2")
)
)
)
)
)
#################################################################
server <- function(input, output) {
output$table <- renderTable({
req(input$variable,input$rate)
data <- data %>%
filter(Rate == input$rate) %>%
dplyr::select(input$variable) %>%
summary() %>%
as.data.frame() %>%
tidyr::separate(Freq, c("Stat", "Value"), sep=":") %>%
tidyr::pivot_wider(names_from =Stat, values_from = Value)
data <- data[, -c(1,2)]
})
output$plot <- renderPlot({
req(input$variable)
if (input$variable == "jaild" | input$variable == "Rate"){
ggplot(data, aes(x = Rate, fill = .data[[as.name(input$variable)]])) +
geom_bar(position = "dodge", width = 0.7) +
if (input$variable == "Rate"){
theme(legend.position = "none")
}
} else {
ggplot(data, aes(x = Rate, y = .data[[as.name(input$variable)]], fill = Rate)) +
geom_boxplot() +
theme(legend.position = "none")
}
})
output$plot2 <- renderPlot({
req(input$train.prop,input$prune)
set.seed(1234)
n <- nrow(data)
ind1 <- sample(c(1:n), round(n*as.numeric(input$train.prop)))
ind2 <- sample(c(1:n)[-ind1], length(c(1:n)[-ind1]))
train.data <- data[ind1,]
valid.data <- data[ind2,]
fit.tree <- rpart(Rate~., data = train.data, method = "class")
ptree <- prune(fit.tree, cp = fit.tree$cptable[which.min(fit.tree$cptable[,"xerror"]),"CP"])
if (input$prune == "view pruned tree"){
rpart.plot(ptree, uniform =TRUE)
} else {
rpart.plot(fit.tree)
}
})
output$table2 <- DT::renderDT({
library(MASS)
set.seed(1234)
n <- nrow(data)
ind1 <- sample(c(1:n), round(n*0.6))
#ind2 <- sample(c(1:n)[-ind1], length(c(1:n)[-ind1]))
ind2 <- setdiff(c(1:n), ind1)
train.data <- data[ind1,]
valid.data <- data[ind2,]
#################################
### fit cart model
fit.tree <- rpart(Rate~., data = train.data, method = "class")
### prune the tree
ptree <- prune(fit.tree, cp = fit.tree$cptable[which.min(fit.tree$cptable[,"xerror"]),"CP"])
### predict using the validation data on the pruned tree
pred <- predict(ptree, newdata = valid.data[,-6], type = "class")
### lda
#lda.model <- lda(train.data[,-6], train.data[,6])
lda.model <- lda(Rate~., data = train.data)
lda.pred <- predict(lda.model, newdata = valid.data[,-6])
### create a classification table
length(lda.model)
x <- pred == valid.data[,6]
CCR <- length(x[x == TRUE])/nrow(valid.data)
MCR <- 1 - CCR
CR <- c(CCR, MCR)
z <- lda.pred$class == valid.data[,6]
lda.CCR <- length(z[z == TRUE])/nrow(valid.data)
lda.MCR <- 1 - lda.CCR
lda.CR <- c(lda.CCR, lda.MCR)
y <- cbind(CR, lda.CR)
y <- as.data.frame(y)
colnames(y) <- c("CART", "LDA")
rownames(y) <- c("CCR", "MCR")
#y
DT::datatable(y, options=list(dom = "t")) %>%
formatRound(columns = c(1,2), digits = 6) %>%
formatStyle(columns = colnames(y[which.max(y[1,])]), background = "green")
#colnames(y[1])
#colnames(y[which.max(y[1,])])
},
rownames = TRUE)
}
?formatStyle
?formatRound()
#################################################################
shinyApp(ui, server)
and here is some of my data:
"beertax","jaild","vmiles","unrate","perinc","Rate"
1.53937947750092,"no",7.23388720703125,14.3999996185303,10544.15234375,1
1.78899073600769,"no",7.83634765625,13.6999998092651,10732.7978515625,1
1.71428561210632,"no",8.262990234375,11.1000003814697,11108.791015625,1
1.65254235267639,"no",8.7269169921875,8.89999961853027,11332.626953125,1
1.60990703105927,"no",8.952853515625,9.80000019073486,11661.5068359375,1
1.55999994277954,"no",9.1663017578125,7.80000019073486,11944,1
1.50144362449646,"no",9.6743232421875,7.19999980926514,12368.6240234375,1
0.214797139167786,"yes",6.81015673828125,9.89999961853027,12309.0693359375,1
0.206422030925751,"yes",6.58749462890625,9.10000038146973,12693.8076171875,1
0.296703308820724,"yes",6.70997021484375,5,13265.93359375,1
0.381355941295624,"yes",6.7712626953125,6.5,13726.6953125,1
0.371517032384872,"yes",8.1290078125,6.90000009536743,14107.3271484375,1
0.360000014305115,"yes",9.370654296875,6.19999980926514,14241,1
0.346487015485764,"yes",9.815720703125,6.30000019073486,14408.0849609375,1
0.650358021259308,"no",7.20850048828125,9.80000019073486,10267.302734375,1
0.67545872926712,"no",7.1759169921875,10.1000003814697,10433.486328125,1
0.598901093006134,"no",7.08481982421875,8.89999961853027,10916.4833984375,1
0.577330529689789,"no",7.25391796875,8.69999980926514,11149.3642578125,1
0.562435507774353,"no",7.4689990234375,8.69999980926514,11399.380859375,1
0.545000016689301,"no",7.66583056640625,8.10000038146973,11537,1
0.52454286813736,"no",8.02462548828125,7.69999980926514,11760.3466796875,1
0.107398569583893,"no",6.8586767578125,9.89999961853027,15797.1357421875,0
0.103211015462875,"no",7.21629150390625,9.69999980926514,15970.18359375,0
0.0989011004567146,"no",7.61917578125,7.80000019073486,16590.109375,0
0.0953389853239059,"no",7.87406689453125,7.19999980926514,16985.169921875,0
0.0928792580962181,"no",8.03491015625,6.69999980926514,17356.037109375,0
0.0900000035762787,"no",8.18063330078125,5.80000019073486,17846,0
0.0866217538714409,"no",8.531990234375,5.30000019073486,18049.0859375,0
0.214797139167786,"no",7.742841796875,7.69999980926514,15082.3388671875,1
0.206422030925751,"no",7.65606298828125,6.59999990463257,15131.880859375,1
0.197802200913429,"no",7.7078525390625,5.59999990463257,15486.8134765625,0
0.190677970647812,"no",8.09220947265625,5.90000009536743,15569.9150390625,0
0.185758516192436,"no",8.13137451171875,7.40000009536743,15616.0986328125,0
0.180000007152557,"no",8.18202783203125,7.69999980926514,15605,0
0.173243507742882,"no",8.3807685546875,6.40000009536743,15845.04296875,0
0.224343672394753,"no",6.4400537109375,6.90000009536743,17255.369140625,0
0.233563080430031,"no",6.57004296875,6,17744.265625,0
0.248010993003845,"no",6.68019287109375,4.59999990463257,18760.439453125,0
0.239078402519226,"yes",6.97921484375,4.90000009536743,19312.5,0
I know the code works properly - I just want it to be able to run properly on the app. Please help!
I'm building a Shiny Application using R , basically it takes a dataset and runs it through several models - Classification / Regression.
The problem i am facing now is , I take inputs from the user with some being numeric and some being factors. The Factor inputs always have one level since we are using Radiobuttons to select a value.
radioButtons("HomeOwner", "Does the Customer own a home?", choiceNames=c('Yes', 'No'), choiceValues = c(1,0)),
radioButtons("Debt", "Does the Customer has existing debt?", choiceNames=c('Yes', 'No'), choiceValues = c(1,0)),
So my dataframe from the building the model has Factors for 3 variables and so does my input data frame from the user but the levels are one since i need to know if they select Yes or No.
Below is the Dataframe :
When i try to predict using the model created , i get the contrast error because of my input dataframe having factor of 1 in three variables , i need them to be factors or is there any way to solve this?
Edit 1 : Whole App
# Application Start
# Initiating Library
source("Functions.R")
library(shiny)
library(shinythemes)
#########################Start of ShinyApp Code#######################################
# Install the shiny and shinythemes packages
# install.packages('shiny')
# install.packages('shinythemes')
# Create the user interface (ui) where you will take the input and display the output
#ui <- fluidpage()
ui <- fluidPage(shinythemes::themeSelector(),
titlePanel("Assignment-AIPM"),
sidebarLayout(
sidebarPanel(
selectInput("selectds","Select the dataset to work with",
choices = c("Boston Housing Dataset"=1,
"Customer Profit Dataset"=2,
"Financial Dataset"=3,
"Education Tech Dataset"=4)
),
br(),
actionButton("runmodels","Run Models"),
),
mainPanel(
navbarPage("Information",
tabPanel("Input",uiOutput("myInput")),
tabPanel("Output",tableOutput("myOutput")),
tabPanel("Plots",plotOutput("myPlot"))
)
)
)
) # fluidPage
# https://stackoverflow.com/questions/30906325/shiny-use-column-headers-from-read-in-file-as-selectinput-choices - To select
# Input from a datapath using the columns
# https://stackoverflow.com/questions/54205476/how-to-execute-a-function-in-the-shiny-server-depending-on-the-inputid-value-of/54220548
# Function Execution
# Define server function
server <- function(input, output, session)
{
observeEvent(input$runmodels,
{
############################# Boston House Prediction
if(input$selectds == 1 )
{
print("Entering Boston House Prediction Input")
output$myInput <- renderUI({
tagList(tags$h3("Enter the details of the Land:"),
radioButtons("CHAS", "Near Charles River or Not", choiceNames=c('Yes', 'No'), choiceValues = c('1','0')),
numericInput("CRIM", "Criminal Rate 1 - 5", 1, min=1, max=5),
numericInput("ZN", "Proportion of Land Zone over 25,000 SQFT", 1),
numericInput("INDUS", "Proportion of Industrial Business in the town", 1),
numericInput("RM", "Average Number of Rooms Per Dwelling", 1),
numericInput("NOX", "Tenure in No. of Years", 1),
numericInput("AGE", "Proportion of Owner Occupied Buildings prior 1940", 1),
numericInput("DIS", "Weighted Distances to Boston Employment Centre", 1),
numericInput("RAD", "Radial Access to highways", 1),
numericInput("TAX", "Full Value Property rate per 10,000$", 1),
numericInput("PTRATIO", "Pupil - Teacher Ratio in Town", 1),
numericInput("B", "Proportion of Black Population in Town", 1),
numericInput("LSTAT", "Percentage of Lower Status Population", 1),
HTML("<br> <br>")
)
})
data_input = reactive({
data.frame(CHAS = factor(input$CHAS),
CRIM = input$CRIM,
ZN = input$ZN,
INDUS = input$INDUS,
NOX = input$NOX,
RM = input$RM,
AGE = input$AGE,
DIS = input$DIS,
RAD = input$RAD,
TAX = input$TAX,
PTRATIO = input$PTRATIO,
B = input$B,
LSTAT = input$LSTAT)
})
regressor_linear <- boston_linear_reg()
data_output = reactive({
data.frame(Logistic_regression = predict(regressor_linear,type='response',data_input())
)
})
output$myOutput <- renderTable({data_output()})
}
############################################### Customer Profit
if(input$selectds == 2 )
{
print("Entering Customer Profit User Input")
output$myInput <- renderUI({
tagList(tags$h3("Enter the details of the customer:"),
radioButtons("Online", "Online Customer?", choiceNames=c('Yes', 'No'), choiceValues = c('1','0')),
radioButtons("Age", "Whats your Customer Age Group?", choiceNames=c('0-10','10-20','20-30','30-40','40-50','50-60','60-70'), choiceValues = c('1','2','3','4','5','6','7')),
radioButtons("Income", "Whats your Customer Income Group?", choiceNames=c('5k-10k','10k-15k','15k-20k','20k-25k','25k-30k','30k-35k','35k-40k','40k-50k','50k+'), choiceValues = c('1','2','3','4','5','6','7','8','9')),
numericInput("Tenure", "Tenure in No. of Years", 1),
HTML("<br> <br>"))
})
data_input = reactive({
data.frame(Online = as.integer(input$Online),
Age = as.integer(input$Age),
Inc = as.integer(input$Income),
Tenure = as.numeric(input$Tenure))
})
regressor_linear <- customer_linear_reg()
classifier_Rforest <- customer_RForest_Regression()
classifier_NNet <- customer_NeuralNet()
data_output = reactive({
data.frame(Linear_regression = predict(regressor_linear,data_input()),
Random_Forest_Prediction = predict(classifier_Rforest,data_input()),
Neural_Net_Prediction = as.data.frame(h2o.predict(classifier_NNet, newdata = as.h2o(data_input())))
)
})
output$myOutput <- renderTable({data_output()})
}
########################## Financial set
if(input$selectds == 3 )
{
print("Entering Finanical User Input")
output$myInput <- renderUI({
tagList(numericInput("Age", "Please enter the Customer Age(1-100)", 25, min=1, max=100),
numericInput("Income", "Please enter Customer monthly Income(0-100000$)", 3500, min=0, max=100000),
radioButtons("HomeOwner", "Does the Customer own a home?", choiceNames=c('Yes', 'No'), choiceValues = c(1,0)),
radioButtons("Debt", "Does the Customer has existing debt?", choiceNames=c('Yes', 'No'), choiceValues = c(1,0)),
numericInput("EmpPeriod", "Please enter the Customer employement period in months", 45),
numericInput("AccPeriod", "Please enter Customer Account Age in months",45),
numericInput("Amount", "Please enter Amount Requested($)",1000),
radioButtons("PaySchedule", "Please enter Pay Schedule", choiceNames=c('bi-weekly', 'weekly', 'semi-monthly','monthly'), choiceValues = c(1,2,3,4)),
numericInput("CurrAddress", "Please enter the Customer currnt address period in months", 45),
numericInput("RiskScore", "Please enter Customer Risk Score (1-100000",40000),
numericInput("Enquiry", "Please enter Customer enquiries last month",5),
actionButton("Predict", "Predict Sanction"))
})
observeEvent(input$Predict, {
data_input = reactive({
data.frame(
home_owner = factor(input$HomeOwner),
age = as.numeric(input$Age),
income = as.numeric(input$Income),
has_debt = factor(input$Debt),
amount_requested = input$Amount,
employment_period = input$EmpPeriod,
personal_account_period = input$AccPeriod,
pay_schedule = factor(input$PaySchedule),
current_address_period = input$CurrAddress,
inquiries_last_month = as.integer(input$Enquiry),
risk_score = input$RiskScore
)
})
logistic_regressor = financial_logistic_regression()
Single_DT = financial_DT()
#classifier_svm = financial_svm()
str(data_input())
data_output = reactive({
data.frame(Logistic_regression = predict(logistic_regressor,type='response',newdata=data_input()),
#Support_vector_machine = predict(classifier_svm, type = 'response', newdata = data_input())
Single_Decision_Tree = predict(Single_DT$classifier, type = 'class', newdata = data_input())
)
})
output$myPlot <- renderPlot({rpart.plot::rpart.plot(Single_DT$classifier)})
output$myOutput <- renderTable({data_output()})
})
}
Functions.R
#Functions for Shiny Assignement
library(caret)
library(ROCR)
library(Metrics)
library(dplyr)
library(caTools)
library(e1071)
library(zoo)
library(car)
library(rpart)
library(randomForest)
library(rpart.plot)
library(h2o)
library(data.table)
# Global Datasets
bostonds <- read.csv('Datasets/02_Boston.csv')
customerds <- read.csv('Datasets/01_CustomerProfit_Regression.csv')
financialds <- read.csv('Datasets/04_P39_Financial_Data.csv')
edtechds <- read.csv('Datasets/05_Lead_Scoring.csv')
boston_linear_reg <- function()
{
set.seed(1234)
data_nomiss = bostonds %>% select(CRIM,ZN,INDUS,CHAS,NOX,RM,AGE,DIS,RAD,
TAX,PTRATIO,B,LSTAT,MEDV) %>% na.omit()
data_nomiss$CHAS = factor(data_nomiss$CHAS)
regressor_lm = lm(formula = MEDV ~ .,data=data_nomiss)
return(regressor_lm)
#medv_predict = predict(regressor,test_ds)
}
customer_linear_reg <- function()
{
data_nomiss = customerds %>% select(Profit,Online,Age,Inc,Tenure) %>% na.omit()
#data_nomiss$Online = factor(data_nomiss$Online)
set.seed(123)
regressor_lm = lm(formula = Profit ~ Online + Inc + Age + Tenure
, data = data_nomiss,na.action = na.omit)
str(data_nomiss)
return(regressor_lm)
#profit_predict = predict(regressor, newdata=test_set)
}
customer_RForest_Regression <- function()
{
######## Data Processing and Cleanup starts here
dataset = customerds
# Creating a new dataset called 'data_nomiss' which will have no missing data
data_nomiss = dataset %>%
select(Profit,Online,Age,Inc,Tenure) %>%
na.omit()
#data_nomiss$Online = factor(data_nomiss$Online)
#data_nomiss$Age = factor(data_nomiss$Age, labels = c('0-10','10-20','20-30','30-40','40-50','50-60','60-70'),levels = c('1','2','3','4','5','6','7'))
#data_nomiss$Inc = factor(data_nomiss$Inc, labels = c('5k-10k','10k-15k','15k-20k','20k-25k','25k-30k','30k-35k','35k-40k','40k-50k','50k+'),levels = c('1','2','3','4','5','6','7','8','9'))
# Factor Variables
#data_nomiss[,1] = scale(data_nomiss[,1])
#data_nomiss[,5] = scale(data_nomiss[,5])
########### Data Processing and Cleanup ends here
set.seed(123)
classifier = randomForest(Profit ~ .,data=data_nomiss,na.action = na.omit,ntree=100)
return(classifier)
}
customer_NeuralNet <- function()
{
dataset = customerds
data_nomiss = dataset %>%
select(Profit,Online,Age,Inc,Tenure) %>%
na.omit()
set.seed(123)
h2o.init(nthreads = -1)
classifier = h2o.deeplearning(y = 'Profit',
training_frame = as.h2o(data_nomiss),
activation = 'Tanh',
hidden = c(10),
epochs = 100,
train_samples_per_iteration = -2)
return(classifier)
}
############################### Financial Dataset
financial_pre_process <- function(ds)
{
####################Data Processing and Clean up Start#############################
data_nomiss = ds %>% select(age,pay_schedule,home_owner,income,
months_employed,years_employed,current_address_year,
personal_account_m,personal_account_y,has_debt,
amount_requested,risk_score,risk_score_2,
risk_score_3,risk_score_4,risk_score_5,
ext_quality_score,ext_quality_score_2,
inquiries_last_month,e_signed) %>% na.omit()
data_nomiss$e_signed = factor(data_nomiss$e_signed)
data_nomiss$home_owner = factor(data_nomiss$home_owner)
data_nomiss$has_debt = factor(data_nomiss$has_debt)
data_nomiss$pay_schedule = factor(data_nomiss$pay_schedule,
levels = c('weekly','bi-weekly','monthly','semi-monthly'),
labels = c(1,2,3,4))
data_nomiss$employment_period = data_nomiss$months_employed + (data_nomiss$years_employed * 12)
data_nomiss$personal_account_period = data_nomiss$personal_account_m + (data_nomiss$personal_account_y * 12)
data_nomiss$current_address_period = data_nomiss$current_address_year * 12
data_nomiss = select(data_nomiss,-c(months_employed,years_employed,personal_account_m,personal_account_y,current_address_year))
data_nomiss[,1] = scale(data_nomiss[,1]) # Age
data_nomiss[,4] = scale(data_nomiss[,4]) # Income
data_nomiss[,6:14] = scale(data_nomiss[,6:14]) # Amount Requested -> Risk score
data_nomiss[,16:18] = scale(data_nomiss[,16:18]) # Created Columns
data_nomiss[,1] = apply(data_nomiss[,1], 1, as.numeric)
data_nomiss[,4] = apply(data_nomiss[,4], 1, as.numeric)
return(data_nomiss)
####################Data Processing and Clean up End#############################
}
financial_logistic_regression <- function()
{
ds = financialds
set.seed(1234)
data_nomiss = financial_pre_process(ds)
str(data_nomiss)
classifier_log = glm(formula = e_signed ~ age+pay_schedule+current_address_period+home_owner+income+employment_period+has_debt+amount_requested+personal_account_period+risk_score+inquiries_last_month,
family = binomial,
data = data_nomiss)
return(classifier_log)
}
financial_svm <- function()
{
ds = financialds
set.seed(1234)
data_nomiss = financial_pre_process(ds)
classifier_svm = svm(formula = e_signed ~ age+pay_schedule+current_address_period+home_owner+income+employment_period+has_debt+amount_requested+personal_account_period+risk_score+inquiries_last_month,
data = data_nomiss,
type = 'C-classification',
kernel = 'radial')
return(classifier_svm)
}
financial_DT <- function()
{
ds = financialds
set.seed(1234)
data_nomiss = financial_pre_process(ds)
classifier_DT = rpart(formula = e_signed ~ age+pay_schedule+current_address_period+home_owner+income+employment_period+has_debt+amount_requested+personal_account_period+risk_score+inquiries_last_month,
data = data_nomiss)
result <- list()
result$classifier <- classifier_DT
result$plot <- rpart.plot::rpart.plot(classifier_DT)
return(result)
}
financial_RForest <- function()
{
ds = financialds
set.seed(1234)
data_nomiss = financial_pre_process(ds)
classifier_RForest = randomForest(x= training_set[-15],
y= training_set$e_signed,
ntree=1500)
result <- list()
result$classifier <- classifier_RForest
result$plot <- rpart.plot::rpart.plot(classifier_RForest)
return(result)
}
}
My form automatically updates the output before I press the Submit button. I read the description of "Submit" button and it says "Forms that include a submit button do not automatically update their outputs when inputs change, rather they wait until the user explicitly clicks the submit button". I am not sure if there's anything wrong.
For your information, here is my code. Data is from UCI (adult data)
Server.R
library(shiny)
library(caret)
predictSalary <- function(input){
adultData <- read.table("adult.data", header = FALSE, sep = ",", strip.white = TRUE)
adultName <- read.csv("adult.name.csv", header = FALSE, sep = ",", stringsAsFactors = FALSE)
names(adultData) <- adultName[, 1]
#Only select several attributes
selected <- c("age", "education", "marital.status", "relationship", "sex", "hours.per.week", "salary")
#selected <- c("age", "hours.per.week", "salary")
adultData <- subset(adultData, select = selected)
#The data is big, we only take 20% for the training
trainIndex = createDataPartition(adultData$salary, p=0.20, list=FALSE)
training = adultData[ trainIndex, ]
set.seed(33833)
modFit <- train(salary ~ ., method = "rpart", data=training)
predict(modFit, newdata = input)
}
shinyServer(
function(input, output) {
dataInput <- reactive({
age <- input$age
edu <- as.factor(input$edu)
marritalstat <- input$marritalstat
relationship <- input$relationship
sex <- input$sex
hours <- input$hours
data.frame(age = age,
education = edu,
marital.status = marritalstat,
relationship = relationship,
sex = sex,
hours.per.week = hours)
# age <- input$age
# hours <- input$hours
# data.frame(age = age, hours.per.week = hours)
})
# dat <- c(input$age, input$edu, input$marritalstat,
# input$relationship, input$sex, input$hours)
output$prediction <- renderPrint({predictSalary(dataInput())})
}
)
Ui.R
library(shiny)
shinyUI(
pageWithSidebar(
# Application title
headerPanel("Salary prediction"),
sidebarPanel(
numericInput('age', 'Age', 40, min = 17, max = 90, step = 1),
selectInput('edu', 'Education',
c("Bachelors"="Bachelors",
"Some-college"="Some-college",
"11th"="11th",
"HS-grad"="HS-grad",
"Prof-school"="Prof-school",
"Assoc-acdm"="Assoc-acdm",
"Assoc-voc"="Assoc-voc",
"9th"="9th",
"7th-8th"="7th-8th",
"12th"="12th",
"Masters"="Masters",
"1st-4th"="1st-4th",
"10th"="10th",
"Doctorate"="Doctorate",
"5th-6th"="5th-6th",
"Preschool"="Preschool")),
radioButtons('marritalstat', 'Marrital Status',
c("Married-civ-spouse" = "Married-civ-spouse",
"Divorced" = "Divorced",
"Never-married" = "Never-married",
"Separated" = "Separated",
"Widowed" = "Widowed",
"Married-spouse-absent" = "Married-spouse-absent",
"Married-AF-spouse" = "Married-AF-spouse")),
radioButtons('relationship', 'Relationship',
c("Wife" = "Wife",
"Own-child" = "Own-child",
"Husband" = "Husband",
"Not-in-family" = "Not-in-family",
"Other-relative" = "Other-relative",
"Unmarried" = "Unmarried")),
radioButtons('sex', 'Sex', c("Male", "Female")),
numericInput('hours', 'Hours per week', 40, min = 1, max = 99, step = 1),
submitButton('Submit')
),
mainPanel(
h3('Results of prediction'),
h4('The predicted salary is '),
verbatimTextOutput("prediction"),
h3('Prediction of salary'),
p('The application is designed to predict whether somebodys salary is greater or smaller than 50k.
The data is extracted from the adult data, provided by UCI database. In order to predict a salary, users need to
provide information of the person whom they would like to make prediction on. After filling in necessary information,
users will press "Submit". The information includes:'),
p(' - Age: must be from 17 to 90'),
p(' - Education'),
p(' - Marital status'),
p(' - Relationship'),
p(' - Gender'),
p(' - Total work hours per week: must be from 1 to 99')
)
)
)
I found the solution by using actionButton in replacement of submitButton. However, I think that there must be an ideal solution with using submitButton.