library(shiny)
library(shinydashboard)
library(leaflet)
library(data.table)
library(ggplot2)
library(usl)
ui <- pageWithSidebar(
headerPanel("CSV Viewer"),
sidebarPanel(
fileInput('file1', 'Choose CSV File',
accept=c('text/csv','text/comma-separated-values,text/plain','.csv')),
tags$hr(),
checkboxInput('header', 'Header', TRUE),
fluidRow(
column(6,radioButtons("xaxisGrp","X-Axis:", c("1"="1","2"="2"))),
column(6,checkboxGroupInput("yaxisGrp","Y-axis:", c("1"="1","2"="2")))
),
radioButtons('sep', 'Separator',
c(Comma=',', Semicolon=';',Tab='\t'), ','),
radioButtons('quote', 'Quote',
c(None='','Double Quote'='"','Single Quote'="'"),'"'),
uiOutput("choose_columns")
),
mainPanel(
tabsetPanel(
tabPanel("Data", tableOutput('contents')),
tabPanel("Plot",plotOutput("plot")),
tabPanel("Summary",uiOutput("summary"))
)
)
)
####server
server <- function(input, output,session) {
dsnames <- c()
u<-
data_set <- reactive({
inFile <- input$file1
data(specsdm91)
if (is.null(inFile))
return(specsdm91)
data_set<-read.csv(inFile$datapath, header=input$header,
sep=input$sep, quote=input$quote)
})
output$contents <- renderTable({data_set()})
observe({
dsnames <- names(data_set())
cb_options <- list()
cb_options[ dsnames] <- dsnames
updateRadioButtons(session, "xaxisGrp",
label = "X-Axis",
choices = cb_options,
selected = "")
updateCheckboxGroupInput(session, "yaxisGrp",
label = "Y-Axis",
choices = cb_options,
selected = "")
})
output$choose_dataset <- renderUI({
selectInput("dataset", "Data set", as.list(data_sets))
})
usl.model <- reactive({
df <- data_set()
# print(df)
df2 <- df[,c(input$xaxisGrp, input$yaxisGrp)]
#gp <- NULL
if (!is.null(df)){
xv <- input$xaxisGrp
yv <- input$yaxisGrp
print(xv)
print(yv)
if (!is.null(xv) & !is.null(yv)){
if (sum(xv %in% names(df))>0){ # supress error when changing files
usl.model <- usl(as.formula(paste(yv, '~', xv)), data = df)
return(usl.model())
}
}
}
#return(gp)
}
)
##plot
output$plot = renderPlot({
plot(usl.model())
} )
##
# output$summary <- renderUI({
# summary(usl.model())
#})
##
output$choose_columns <- renderUI({
if(is.null(input$dataset))
return()
colnames <- names(contents)
checkboxGroupInput("columns", "Choose columns",
choices = colnames,
selected = colnames)
})
}
shinyApp(ui, server)
As you can see I have the df printed. Any ideas?
EDIT: Please give a reproducible example of your data. Without that, it's hard to imagine what the data types are. In general, I think you have potentially two problems:
What is gp? You need to return not gp but usl.model
Your renderUI is not passing a UI object (i.e. not something the output function will know what to do with).
Your problem is that usl.model is not actually being saved anywhere, because it's being called within renderPlot, which returns only the plot. Since you want usl.model to be consumed by two functions, you should take one of the following approaches.
Approach 1:
Define a reactive function for usl.model and reference it in your two output functions.
usl.model <- reactive({
# some calculations probably ending in
usl.model <- usl(as.formula(paste(yv, '~', xv)), data = df)
usl.model
})
This allows you to reference your model output as usl.model() (the parenthesis are important!), e.g.
output$plot <- renderPlot( plot(usl.model(), add=TRUE) )
Approach 2
Create a reactiveValues() variable to store your usl.model as calculated in the plot function.
usl.model <- reactiveValues(data = NULL)
output$plot = renderPlot({
# some calculations probably ending in
usl.model$data <- usl(as.formula(paste(yv, '~', xv)), data = df)
})
You can then refer to your model output anywhere as usl.model$data
Approach two is possibly worse because it requires the plot function to be run first.
Related
I am making a shiny where I can read a CSV file, and then be able to replace a selected column with a new value (which in this case replaced by 0).
I usually use a mutate function to do this.
How to use mutate function properly in shiny, when the selected column is also an input?
ui <- fluidPage(fileInput('file1', h2('Dataset Settings'),
accept=c('text/csv', 'text/comma-separated-values,text/plain', '.csv')),
tags$hr(),
selectInput(inputId = "replaceCol",
label = "Select numeric with missing value",
choices = c()),
actionButton(inputId = "confirm",
label = "Replace with 0"),
tags$hr(),
dataTableOutput("Original")
)
server <- function(input, output, session){
data_set <- reactive({
inFile <- input$file1
read.csv(inFile$datapath)
})
observe({
req(input$file1)
temp <- colnames(data_set())
col <- list()
col[temp] <- temp
updateSelectInput(session,
inputId = "replaceCol",
choices = col,
selected = "")
})
output$Original <- renderDataTable({
data_set()
})
observeEvent(input$confirm,{
data_set() <- mutate(data_set(), replace(input$replaceCol, TRUE, 0))
})
}
shinyApp(ui = ui, server = server)
Your code has several issues:
if a UI element depends on some calculation from the server, it is best to use renderUI
you can't directly assign something to the output of a reactive function
if you want to dynamically generate variable names in dplyr, it's a bit more complicated
Therefore, I use a reactiveVal to store your dataset and update it, if a column is changed. I'm not completely satisfied with the use of an observer to update the data_set() when a new file is chosen, I'm happy to hear if someone has a better solution.
library(shiny)
library(dplyr)
ui <- fluidPage(fileInput('file1', h2('Dataset Settings'),
accept=c('text/csv', 'text/comma-separated-values,text/plain', '.csv')),
tags$hr(),
uiOutput(outputId = "UI_replaceCol"),
actionButton(inputId = "confirm",
label = "Replace with 0"),
tags$hr(),
dataTableOutput("Original")
)
server <- function(input, output, session){
# reactive variable to store the data
data_set <- reactiveVal()
observeEvent(input$file1, {
inFile <- input$file1
data <- read.csv(inFile$datapath)
data_set(data)
})
output$UI_replaceCol <- renderUI({
req(data_set())
col <- colnames(data_set())
selectInput(inputId = "replaceCol",
label = "Select numeric with missing value",
choices = col)
})
output$Original <- renderDataTable({
data_set()
})
observeEvent(input$confirm,{
data <- data_set() %>%
mutate(!!as.symbol(input$replaceCol) :=
replace(!!as.symbol(input$replaceCol), TRUE, 0))
data_set(data)
})
}
shinyApp(ui = ui, server = server)
I have created an R shiny app to produce k-means clustering results. The app is not producing results. However, it shows output in the console. Further, it also works fine when it knitted in Rmarkdown. If you have any opinion on the code part or any other suggestion to resolve this issue. Do let me know.
Here is my code.
library(shiny)
library(dplyr)
library(cluster)
ui <- pageWithSidebar(
headerPanel("Cluster Analysis"),
sidebarPanel(
fileInput('file1', 'Choose CSV File',
accept=c('text/csv','text/comma-separated-values,text/plain','.csv')),
tags$hr(),
checkboxInput('header', 'Header', TRUE),
helpText("You will be able to see the variable name after you add in a datafile"),
fluidRow(
column(6,checkboxGroupInput("variable","Select Variables:", c("1"="1","2"="2")))
),
sliderInput("kvalue", "Select number of clusters",
value = 3, min = 3, max= 6),
radioButtons('sep', 'Separator',
c(Comma=',', Semicolon=';',Tab='\t'), ','),
uiOutput("choose_columns")
),
mainPanel(
tabsetPanel(
tabPanel("Result", verbatimTextOutput("result")),
tabPanel("Data", tableOutput('contents'))
)
)
)
server <- function(input, output,session) {
dsnames <- c()
data_set <- reactive({
inFile <- input$file1
if (is.null(inFile))
return()
data_set <-read.csv(inFile$datapath, header=input$header,
sep=input$sep)
})
output$contents <- renderTable({data_set()})
observe({
dsnames <- names(data_set())
cb_options <- list()
cb_options[ dsnames] <- dsnames
updateCheckboxGroupInput(session, "variable",
label = "Select Variables",
choices = cb_options,
selected = "")
})
output$choose_dataset <- renderUI({
selectInput("dataset", "Data set", as.list(data_sets))
})
dfInput <- reactive({
data <- data_set()
if(is.null(data))
return()
data %>%
dplyr::select(input$variable)
}
)
output$result <- renderPrint(
{
dfin <- dfInput()
gp <- NULL
if (!is.null(dfin)){
df <- dfin
test <- na.omit(df)
test1 <- scale(test)
test2 <- daisy(test1)
seg.k <- kmeans(test2, centers=input$kvalue, nstart=25)
df$segment <- seg.k$cluster
test2 <- df%>%
dplyr::group_by(segment)%>%
dplyr::summarise_all(list(mean))
print(test2)
}
return(gp)
}
)
output$choose_columns <- renderUI({
if(is.null(input$dataset))
return()
colnames <- names(contents)
checkboxGroupInput("columns", "Choose columns",
choices = colnames,
selected = colnames)
})
}
shinyApp(ui, server)
I have made a shiny app which takes in any data and shows column names depending on the data.
c1 <- rnorm(10,0,1)
c2 <- c(rep("txA",5),rep("txB",5))
c3 <- c(1:4,1:4,1:2)
c4 <- rep(LETTERS[1:5],2)
mydata <- data.frame(c1,c2,c3,c4)
ui <- fluidPage(
fileInput(inputId = "file",
label = "import file"),
tableOutput("tb"),
sidebarLayout(
sidebarPanel(
uiOutput(outputId = "aa")
),
mainPanel(textOutput("a"),
verbatimTextOutput("info"),
verbatimTextOutput("summary"),
plotOutput("plot", click = "plot_click")
)
)
)
server <- function(input,output) {
output$aa <- renderUI({
validate(need(input$file != "", ""))
mydata <- read.csv(input$file$datapath)
selectInput(inputId = "aa", #can be any name?
label="Select:",
choices = colnames(mydata))
})
output$tb <- renderTable({
data <- input$file
if (is.null(data))return()
read.table(data$datapath,sep=",")
})
output$summary <- renderPrint({
summary(mydata)
})
output$plot <- renderPlot({
plot(mydata)
})
output$info <- renderText({
paste0("x=", input$plot_click$x, "\ny=", input$plot_click$y)
})
}
shinyApp(ui=ui, server=server)
If I run this I get the following:
I am trying to make a shiny app which shows a basic plot depending on the columns that I choose. How would I do this?
Something like this would do, make sure to uncomment the file input
library(shiny)
c1 <- rnorm(10,0,1)
c2 <- c(rep("txA",5),rep("txB",5))
c3 <- c(1:4,1:4,1:2)
c4 <- rep(LETTERS[1:5],2)
mydata <- data.frame(c1,c2,c3,c4)
ui <- fluidPage(
fileInput(inputId = "file",
label = "import file"),
tableOutput("tb"),
sidebarLayout(
sidebarPanel(
uiOutput(outputId = "aa")
),
mainPanel(textOutput("a"),
verbatimTextOutput("info"),
verbatimTextOutput("summary"),
plotOutput("plot", click = "plot_click")
)
)
)
server <- function(input,output) {
output$aa <- renderUI({
#validate(need(input$file != "", ""))
#mydata <- read.csv(input$file$datapath)
## Since your output$aa already has name aa you cant use it twice!
selectInput(inputId = "aa2", #can be any name?
label="Select:",
choices = colnames(mydata))
})
output$tb <- renderTable({
data <- input$file
if (is.null(data))return()
read.table(data$datapath,sep=",")
})
mysubsetdata <- eventReactive(input$aa2,{
mydata[[input$aa2]]
})
output$summary <- renderPrint({
summary(mysubsetdata())
})
output$plot <- renderPlot({
plot(mysubsetdata())
})
output$info <- renderText({
paste0("x=", input$plot_click$x, "\ny=", input$plot_click$y)
})
}
shinyApp(ui=ui, server=server)
Added eventReactive to listen to selectInput
All widgets must have unique id so you cannot use aa twice, one for renderui and one for selectInput
I am building an App with an upload function and a filter function for category variables. That way, users are able to do a bit of data manipulation by specifying columns and values. However, the filter function does not work. The code is simplified as following:
#ui.R
library(shiny)
fluidPage(
titlePanel("Test Dynamic Column Selection"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose CSV File',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv')),
hr(),
checkboxInput('header', 'Header', TRUE),
radioButtons('sep', 'Separator',
c(Comma=',',
Semicolon=';',
Tab='\t'),
','),
hr(),
uiOutput("choose_columns"),
hr(),
uiOutput("choose_column"),
textInput('column_value', label = 'Value'),
actionButton('filter', label = 'Filter')
),
mainPanel(
tableOutput('contents')
)
)
)
#server.R
library(shiny)
function(input, output) {
uploaded_data <- reactive({
inFile <- input$file1
read.table(inFile$datapath, header=input$header, sep=input$sep, quote=input$quote)
})
react_vals <- reactiveValues(data = NULL)
output$choose_columns <- renderUI({
if(is.null(input$file1))
return()
colnames <- names(react_vals$data)
checkboxGroupInput("choose_columns", "Choose columns",
choices = colnames,
selected = colnames)
})
output$choose_column <- renderUI({
if(is.null(input$file1))
return()
is_factor <- sapply(react_vals$data, is.factor)
colnames <- names(react_vals$data[, is_factor])
selectInput("choose_column", "Choose column", choices = colnames)
})
observeEvent(input$file1, react_vals$data <- uploaded_data())
observeEvent(input$choose_columns, react_vals$data <- react_vals$data[, input$choose_columns])
# This line of code does not work :(
observeEvent(input$filter, react_vals$data <- subset(react_vals$data, input$choose_column != input$column_value))
output$contents <- renderTable(react_vals$data)
}
I think there were multiple problems with your app, I try to explain it step by step:
input$choose_columns is dependent on the react_vals$data reactive value, and thus when unchecking a checkbox, Shiny assigns a new value to react_vals$data with one less column, and then rerenders the input$choose_columns UI, so that there is one less checkbox available. (Same thing with the input$choose_column selectInput)
Your code:
colnames <- names(react_vals$data)
Replacement code:
colnames <- names(uploaded_data())
Use req() when checking whether a file is uploaded, UI is rendered, etc. It is best practice.
Your code:
if(is.null(input$file1)) return()
Replacement code:
req(input$file1)
Filtering is not working. Basically why it didn't work is that it tries to subset based on comparing two strings from input$choose_column and input$column_value.
i.e.: "Column name A" != "Value: something"
Which returns TRUE usually for every rows, and it ended up not filtering at all.
I came up with 2 solutions, they are a little bit ugly, so if someone comes up with a better solution, feel free to comment/edit.
#server.R
library(shiny)
function(input, output) {
uploaded_data <- reactive({
inFile <- input$file1
read.table(inFile$datapath, header=input$header, sep=input$sep, quote=input$quote)
})
react_vals <- reactiveValues(data = NULL)
output$choose_columns <- renderUI({
req(input$file1)
colnames <- names(uploaded_data())
checkboxGroupInput("choose_columns", "Choose columns",
choices = colnames,
selected = colnames)
})
output$choose_column <- renderUI({
req(input$file1)
is_factor <- sapply(uploaded_data(), is.factor)
colnames <- colnames(uploaded_data()[is_factor])
selectInput("choose_column", "Choose column", choices = colnames)
})
observeEvent(input$file1, react_vals$data <- uploaded_data())
observeEvent(input$choose_columns, react_vals$data <- uploaded_data()[, input$choose_columns])
observeEvent(input$filter, {
react_vals$data <-
#Option A
eval(parse(text = sprintf("subset(uploaded_data(), %s != '%s')", input$choose_column, input$column_value)))
#Option B
#subset(uploaded_data(), uploaded_data()[, which(names(uploaded_data()) == input$choose_column)] != input$column_value)
})
output$contents <- renderTable(react_vals$data)
}
shinyApp(ui, server)
I need to create some sliders based on number items in a vector:
ui code:
library(shiny)
library(shinydashboard)
library(leaflet)
library(data.table)
library(ggplot2)
library(ggthemes)
library(usl)
ui<-dashboardPage(skin="green",
dashboardHeader(title = "ADM Logical Capacity Planning Service",titleWidth = 350),
dashboardSidebar(
sidebarMenu(
menuItem("Visualize & Create Model", tabName = "visualize",icon=icon("area-chart")),
menuItem("Forecast", tabName = "capacity", icon=icon("line-chart")) )
),
dashboardBody(
tags$head(tags$style(HTML('
.skin-blue .main-header .logo {
background-color: #3c8dbc;
}
.menuItem .main-header .logo:hover {
background-color: #3c8dbc;
}
'))),
tabItems(
tabItem("capacity",
fluidRow(
column(3,
wellPanel(
span("Given the growth rate, forecast the underlying dependent variable")
),
wellPanel(
# Create a uiOutput to hold the sliders
uiOutput("sliders")
),
# Generate a row with a sidebar
#sliderInput("capacity", "Growth Rate in Volume:", min=0, max=100, value=0,post="%"),
#br(),
#sliderInput("add_capacity", "Add Capacity in %:", min=0, max=100, value=0,post="%"),
br(),
wellPanel(
actionButton("calcbtn", "Calculate Forecast")
)
),
mainPanel(
h4("Prediction"),
verbatimTextOutput("forecast_summary"),
h4("Available Capacity"),
verbatimTextOutput("capacity_summary")
#h4("Peak Capacity"),
#verbatimTextOutput("peak_capacity")
)
)
),
tabItem("visualize",
pageWithSidebar(
headerPanel("Logical Capacity Planning Dashboard"),
sidebarPanel(
fileInput('file1', 'Upload CSV File to Create a Model',
accept=c('text/csv','text/comma-separated-values,text/plain','.csv')),
tags$hr(),
checkboxInput('header', 'Header', TRUE),
fluidRow(
column(6,checkboxGroupInput("xaxisGrp","X-Axis:", c("1"="1","2"="2"))),
column(6,radioButtons("yaxisGrp","Y-axis:", c("1"="1","2"="2")))
),
radioButtons('sep', 'Separator',
c(Comma=',', Semicolon=';',Tab='\t'), ','),
radioButtons('quote', 'Quote',
c(None='','Double Quote'='"','Single Quote'="'"),'"'),
uiOutput("choose_columns")
),
mainPanel(
tabsetPanel(
tabPanel("Data", tableOutput('contents')),
tabPanel("Create Model & Plot",plotOutput("plot"),verbatimTextOutput("PeakCapacity")),
tabPanel("Model Summary",verbatimTextOutput("summary"))
)
)
)
)
)
)
)
server code:
server <- function(input, output, session)
{
###
output$sliders <- renderUI({
xv <- input$xaxisGrp
# First, create a list of sliders each with a different name
sliders <- lapply(1:length(xv), function(i) {
inputName <- xv[i]
sliderInput(inputName, inputName, min=0, max=100, value=0, post="%")
})
# Create a tagList of sliders (this is important)
do.call(tagList, sliders)
})
###
observeEvent(input$calcbtn, {
n <- isolate(input$calcbtn)
if (n == 0) return()
output$forecast_summary <- renderPrint({
n<-pred.model()
n<-data.frame(n)
row.names(n)<-NULL
print(n)
})
output$capacity_summary <- renderPrint({
n<-pred.model()
n<-data.frame(n)
row.names(n)<-NULL
#c<-round(peak.scalability(usl.model()),digits=0)
available<-round(((c-n[1,1])/c)*100,digits=0)
row.names(available)<-NULL
print(paste0(available,"%"))
})
# output$peak_capacity <- renderPrint({
# print(paste("Maximum Capacity: ", round(peak.scalability(pred.model()),digits=0)))
# })
output$plot_forecast <- renderPlot({
df <- data_set()
new_df<- pred.model()
print(sliders)
if (!is.null(df)){
xv <- input$xaxisGrp
yv <- input$yaxisGrp
print(xv)
print(yv)
if (!is.null(xv) & !is.null(yv)){
if (sum(xv %in% names(df))>0){ # supress error when changing files
df1<-data.frame(usl.model()$fitted)
colnames(df1)<-c("Model")
df<-cbind(df,df1)
Model=c("Model")
#ggplot(df, aes_string(xv,yv))+geom_point(size=3,colour="blue")+geom_line(data=df, aes_string(xv,Model),colour="orange",size=1)+
#geom_point(data=new_df,aes(new_df[,1],new_df[,2]), colour="red",size=10)+theme_bw()+theme(legend.position = "none")
#max_capacity<-round(peak.scalability(usl.model()),digits=0)
Ninety_Fifth_Perc<-quantile(df[,2], 0.95)
#peak<-round(peak.scalability(usl.model()),digits=0)
#available<-round(((max_capacity-Ninety_Fifth_Perc)/max_capacity)*100,digits=0)
new_d<-pred.model()
ggplot(df, aes_string(xv,yv))+geom_point(size=4,shape=21, fill="blue")+geom_line(data=df, aes_string(xv,Model),colour="orange",size=1)+
geom_point(data=new_df,aes(new_df[,1],new_df[,2]), colour="red",size=10)+
theme_bw()+theme(legend.position = "none")+geom_vline(xintercept=new_df[,1], colour="green",size=1.5)
}
}
}
})
})
###pred function
pred.model <- reactive({
xv <- input$xaxisGrp
yv <- input$yaxisGrp
#latest_df<-do.call(data.frame,setNames(lapply(xv,function(e) vector(typeof(e))),xv))
latest_df<-data.frame()
new_df1 = data.frame()
for(i in 1:length(xv)){
##xv[i]<-as.numeric(input$xv[i])
# capacity<-as.numeric(input$capacity)
#add_capacity<-as.numeric(input$add_capacity)
df <- data_set()
if (!is.null(df)){
if (!is.null(xv) & !is.null(yv)){
if (sum(xv[i] %in% names(df))>0){ # supress error when changing files
#usl.model <- usl(as.formula(paste(yv, '~', xv)), data = df)
#new_growth<-tail(df[,xv],1)*(1+capacity/100)
new_growth<-quantile(df[,xv[i]],0.95)*(1+input$xv[i]/100)
new_cap<-new_growth
new_df1[1,i] = setNames(data.frame(new_cap),xv[i])
row.names(new_df1)<-NULL
}
}
}
}
latest_df=new_df1
prediction<-predict(usl.model(),newdata = latest_df)
prediction<-data.frame(prediction)
prediction<-prediction[1,1]
return(prediction)
})
##end of pred function
###visualize section
dsnames <- c()
data_set <- reactive({
inFile <- input$file1
data(specsdm91)
if (is.null(inFile))
return(specsdm91)
data_set<-read.csv(inFile$datapath, header=input$header,
sep=input$sep, quote=input$quote,stringsAsFactors=F)
})
output$contents <- renderTable({data_set()})
observe({
dsnames <- names(data_set())
cb_options <- list()
cb_options[ dsnames] <- dsnames
updateCheckboxGroupInput(session, "xaxisGrp",
label = "X-Axis",
choices = cb_options,
selected = "")
updateRadioButtons(session, "yaxisGrp",
label = "Y-Axis",
choices = cb_options,
selected = "")
})
output$choose_dataset <- renderUI({
selectInput("dataset", "Data set", as.list(data_sets))
})
usl.model <- reactive({
df <- data_set()
if (!is.null(df)){
xv <- input$xaxisGrp
yv <- input$yaxisGrp
print(xv)
print(yv)
if (!is.null(xv) & !is.null(yv)){
if (sum(xv %in% names(df))>0){ # supress error when changing files
xv <- paste(xv, collapse="+")
lim <- lm(as.formula(paste(yv, '~', xv)), data = df)
return(lim)
}
}
}
})
##plot
output$plot = renderPlot({
df <- data_set()
if (!is.null(df)){
xv <- input$xaxisGrp
yv <- input$yaxisGrp
print(xv)
print(yv)
if (!is.null(xv) & !is.null(yv)){
if (sum(xv %in% names(df))>0){ # supress error when changing files
#plot(as.formula(paste(yv, '~', xv)), data = df, pch = 21)
#plot(usl.model(),add=TRUE)
df1<-data.frame(usl.model()$fitted)
colnames(df1)<-c("Best_Fit_Model")
#df<-cbind(df,df1)
Model<-c("Best_Fit_Model")
df1<-cbind(df[yv],df1)
#max_capacity<-round(peak.scalability(usl.model()),digits=0)
#Ninety_Fifth_Perc<-quantile(df[,2], 0.95)
#peak<-round(peak.scalability(usl.model()),digits=0)
#available<-round(((max_capacity-Ninety_Fifth_Perc)/max_capacity)*100,digits=0)
#new_d<-pred.model()
df.melt=melt(df, id=yv)
xx<-c("value")
ggplot(df.melt,aes_string(x = xx, y = yv)) + geom_point() +facet_wrap(~variable, scale="free")+theme_bw()+
geom_smooth(method="lm", se=F, colour="red")
# p2<-ggplot(df1,aes_string(x = yv, y = Model)) + geom_point() + theme_bw()+
# geom_smooth(method="lm", se=F, colour="red")
}
}
}
} )
##
output$summary <- renderPrint({
summary(usl.model())
})
output$choose_columns <- renderUI({
if(is.null(input$dataset))
return()
colnames <- names(contents)
checkboxGroupInput("columns", "Choose columns",
choices = colnames,
selected = colnames)
})
}
EDIT: You're also referencing xaxisGrp as an input (which it isn't). That's causing some issues. Turns out fixing that (see the example below) makes things work nicely. I didn't realize that! Cool stuff.
Updating based on your comment, you should be able to access each input using bracket notation. Your question is still referencing input$xaxisGrp which doesn't exist, though. I'm also not sure why you're calling renderPlot({}) since nothing's being plotted.
library(shiny)
ui <- shinyUI(
fluidPage(
sidebarLayout(
sidebarPanel(
uiOutput("sliders")
),
mainPanel(
)
))
server <- shinyServer(function(input, output, session) {
xaxisGrp <- c("CPU", "Memory", "Disk")
output$sliders <- renderUI({
xv <- xaxisGrp
sliders <- lapply(1:length(xv), function(i) {
inputName <- xv[i]
sliderInput(inputName, inputName, min=0, max=100, value=0, post="%")
})
do.call(tagList, sliders)
})
output$plot_forecast <- renderPlot({
xv <- xaxisGrp
for(i in 1:length(xv)) {
value <- input[xv[i]]
}
})
})
I'm a little unsure why you're constructing the sliders this way. Have you looked into namespacing? Or even just write 3 separate outputs? For example (you can run this to see each input <key, value> pair):
library(shiny)
ui <- shinyUI(
fluidPage(
sidebarLayout(
sidebarPanel(
uiOutput("slider1"),
uiOutput("slider2"),
uiOutput("slider3"),
uiOutput("sliders")
),
mainPanel(
verbatimTextOutput("inputVals")
)
)
))
server <- shinyServer(function(input, output, session) {
output$slider1 <- renderUI({
sliderInput("CPU2", "CPU2", min=0, max=100, value=0, post="%")
})
output$slider2 <- renderUI({
sliderInput("Memory2", "Memory2", min=0, max=100, value=0, post="%")
})
output$slider3 <- renderUI({
sliderInput("Disk2", "Disk2", min=0, max=100, value=0, post="%")
})
output$sliders <- renderUI({
xv <- c("CPU","Memory","Disk")
sliders <- lapply(1:length(xv), function(i) {
inputName <- xv[i]
sliderInput(inputName, inputName, min=0, max=100, value=0, post="%")
})
do.call(tagList, sliders)
})
output$inputVals <- renderPrint({
print(reactiveValuesToList(input))
})
})
# Run the application
shinyApp(ui = ui, server = server)
In your case, it looks like your inputs are all rendering without any ID (xaxisGrp isn't a valid input in your example). That's bad, they each need a unique one. Namespacing is one way to solve for this by abstracting the UI-generating functions and guarantee unique IDs for each input. Less cumbersome most times (unless, I don't know, you need to dynamically generate them based on some external factor) is to just create multiple individual inputs.
Once you're building the inputs correctly, then to access any given input's value, just use the input$inputId syntax within any reactive context:
output$CPUValue <- renderText({
input$CPU
})