Shiny R Histogram - r

I am using below code to lean Shiny R , when i run this code, it gives me this error:
Warning: Error in hist.default: 'x' must be numeric
[No stack trace available]
library(shiny)
ui <- fluidPage(
selectInput("Ind","Indipendent Variable",choices = names(mtcars)),
selectInput('Dep',' Dependent Variable',choices = names(mtcars)),
plotOutput("BoxPlot"),
plotOutput('Hist'))
server <- function(input, output, session) {
data1 <- reactive({input$Ind})
data2 <- reactive({input$Dep})
output$BoxPlot <- renderPlot({boxplot(get(data2()) ~ get(data1()) , data=mtcars)})
output$Hist <- renderPlot({hist(get(data1())})
}
shinyApp(ui, server)
any help why would it say so ?

Try not to put everything into 1 line as it doesnt improve readability, you can use Google's R Style Guide if you like.To answer your questions you can access the variable via [[]] like so:
library(shiny)
ui <- fluidPage(
selectInput("Ind","Indipendent Variable",choices = names(mtcars)),
selectInput('Dep',' Dependent Variable',choices = names(mtcars)),
plotOutput("BoxPlot"),
plotOutput('Hist')
)
server <- function(input, output, session) {
data1 <- reactive({
input$Ind
})
data2 <- reactive({
input$Dep
})
output$BoxPlot <- renderPlot({
boxplot(get(data2()) ~ get(data1()) , data=mtcars)
})
output$Hist <- renderPlot({
req(data1())
hist(mtcars[[data1()]])
})
}
shinyApp(ui, server)

Related

ShinyApp not rendering plots in R

I am having problems rendering any visualizations on Shiny. I tried many different plots, none of them worked. Here is the code:
library(shiny)
ui <- fluidPage("Comex",
selectInput("paises","Selecione o Destino da Exportação",PAISES$NO_PAIS, selected = PAISES$NO_PAIS[55]),
plotlyOutput(outputId = "table"))
server <- function(input, output){
output$table <- renderTable({
p <- RPostgres::dbGetQuery(con, paste0("SELECT CO_ANO, NO_PAIS, SUM(VL_FOB)
FROM comex
INNER JOIN paises ON comex.CO_PAIS = paises.CO_PAIS
WHERE (SG_UF_MUN = 'AL') AND (NO_PAIS = '",input$paises,"')
GROUP BY NO_PAIS, CO_ANO"))
View(p)
})}
shinyApp(ui, server)
The SQL command seems fine, as I successfully extracted data with this very code outside the shinyApp structure.
The return value from View(.) is NULL, so your renderTable will always be blank; just make it p.
If your ui contains plotlyOutput then replace renderTable with plotly::renderPlotly. The ui-component for shiny::renderTable is shiny::tableOutput.
renderTable is intended for a tabular display of data.frame-like data, not a plot.
Choose either:
ui <- fluidPage(
...,
tableOutput("table")
...
)
server <- function(input, output, session) {
output$table <- renderTable({
# code that returns a data.frame
})
}
or
ui <- fluidPage(
...,
plotlyOutput("myplot")
...
)
server <- function(input, output, session) {
output$myplot <- plotly::renderPlotly({
# ...
plot_lt(...)
})
}

R shiny Handsontable : use dataframe from handsontable

In the below toy example I have a data set datapred. The data set are output to an interactive table using rhandsontable. Then I covert it in a new data.frame with hot_to_r. My issue is that when I wnat to use it in my function prediction(), it send me an error message and the application crash. I don't understand why.
I'm french so I converted in english the message :
Error in as.name: the 'pairlist' object can not be automatically converted to a 'symbol' type.
library(shiny)
library(frailtypack)
library(rhandsontable)
data("readmission", package = "frailtypack")
ui <- fluidPage(
titlePanel("prediction"),
mainPanel(
fluidRow(rHandsontableOutput("hot")),
br(),
plotOutput("pred")
)
)
server <- function(input, output) {
newdata <- subset(readmission,select = c("time","event","id","dukes"))
datapred <- newdata[1,]
data <- reactive({
DF = hot_to_r(input$hot)
DF
})
model <- frailtyPenal(Surv(time,event)~cluster(id)+dukes,n.knots=10,
kappa=10000,data=readmission)
predict <- reactive(
prediction(model, data(),t=200,window=seq(50,1900,50),
MC.sample=100))
output$hot <- renderRHandsontable({
rhandsontable(datapred)
})
data <- reactive({
DF = hot_to_r(input$hot)
DF
})
output$pred <- renderPlot({
plot(predict(),conf.bands=TRUE)
})
}
shinyApp(ui = ui, server = server)
You could simply evaluate the data() first, like this. I also added some checks so you don't get other errors during the initialization
library(shiny)
library(frailtypack)
library(rhandsontable)
data("readmission", package = "frailtypack")
ui <- fluidPage(
titlePanel("prediction"),
mainPanel(
fluidRow(rHandsontableOutput("hot")),
br(),
plotOutput("pred")
)
)
server <- function(input, output) {
newdata <- subset(readmission,select = c("time","event","id","dukes"))
datapred <- newdata[1,]
data <- reactive({
hot <- input$hot
if (!is.null(hot)) hot_to_r(hot)
})
model <- frailtyPenal(Surv(time,event)~cluster(id)+dukes,n.knots=10,
kappa=10000,data=readmission)
predict <- reactive({
dat <- data()
if (!is.null(dat)) {
prediction(model, dat,t=200,window=seq(50,1900,50),
MC.sample=100)
}
})
output$hot <- renderRHandsontable({
rhandsontable(datapred)
})
output$pred <- renderPlot({
pred <- predict()
if (!is.null(pred)) plot(pred, conf.bands = TRUE)
})
}
shinyApp(ui = ui, server = server)

R shinyapp selecting pre-stored data set from checkbox

ui <- fluidPage(
checkboxGroupInput("data", "Select data:",
c("Iris" = "iris",
"Cars" = "mtcars")),
plotOutput("myPlot")
)
server <- function(input, output) {
output$myPlot <- renderPlot({
plot(Sepal.Width ~ Sepal.Length, data = input$data)
})
}
shinyApp(ui, server)
I have a shinyApp where I want the user to select a data set. From there, I want to use that data set to make a simple plot. However, it seems that the user input into the checkbox didn't pass in successfully to the server. How can I get around this?
The typical way to do this in shiny is with switch(), which means you don't need to specify the dataset in your input, you can do it all in the server. In your context:
library(shiny)
ui <- fluidPage(
checkboxGroupInput("data", "Select data:",
c("Iris" = "iris",
"Cars" = "mtcars")),
plotOutput("myPlot")
)
server <- function(input, output) {
dat <- reactive({
switch()
})
output$myPlot <- renderPlot({
dat <- switch(input$data,
"iris" = iris,
"mtcars" = mtcars)
plot(Sepal.Width ~ Sepal.Length, data = get(input$data))
})
}
shinyApp(ui, server)
Note that you could use any strings in the checkboxGroupInput, which makes this a more flexible way to work.

Using results/output from one shiny module to updateSelectInput within another

In figuring out how to use the new shiny modules, I would like to emulate the following app. When the rows of the datatable are clicked and unclicked, it updates the entries in the selectInput box, using updateSelectInput.
library(shiny)
## prepare dataframe -----------------------------------------------------------
df <- mtcars
df$model <- rownames(df)
rownames(df) <- NULL
df <- df[1:10, c(12, 1:5)]
car_names <- data.frame(df$model)
## app -------------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput('car_input', 'Select car:', df$model, multiple = TRUE)
),
mainPanel(
DT::dataTableOutput('table')
)
)
)
server <- function(input, output, session, ...) {
output$table <- DT::renderDataTable(df)
car_rows_selected <- reactive(car_names[input$table_rows_selected, ])
observe({ updateSelectInput(session, 'car_input', selected = car_rows_selected()) })
}
shinyApp(ui = ui, server = server)
I have got most of the way there, but am having difficulty with updating the input box. I wonder if it has something to do with the way the namespaces work, and perhaps requires a nested call to the DFTable module within the Car module, but I'm not sure. I am able to add a textOutput element that prints the expected information from the selected table rows. My code for a single file app is below:
library(shiny)
## prepare dataframe -----------------------------------------------------------
df <- mtcars
df$model <- rownames(df)
rownames(df) <- NULL
df <- df[1:10, c(12, 1:5)]
car_names <- data.frame(df$model)
## select module ---------------------------------------------------------------
CarInput <- function(id){
ns <- NS(id)
selectInput(ns('car_input'), 'Select car:', df$model, multiple = TRUE)
}
Car <- function(input, output, session, ...) {
# I was thinking perhaps I needed to call the DFTable module as a nested module within this Car module
car_rows_selected <- callModule(DFTable, 'id_inner')
observe({ updateSelectInput(session, 'car_input', selected = car_rows_selected()) })
}
## datatable module ------------------------------------------------------------
DFTableOutput <- function(id){
ns <- NS(id)
DT::dataTableOutput(ns('table'))
}
DFTable <- function(input, output, session, ...){
output$table <- DT::renderDataTable(df)
return(reactive(car_names[input$table_rows_selected, ]))
}
## app -------------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
CarInput('id_car'),
textOutput('selected') # NB. this outputs expected values
),
mainPanel(
DFTableOutput('id_table')
)
)
)
server <- function(input, output, session, ...) {
callModule(Car, 'id_car')
callModule(DFTable, 'id_table')
output$selected <- callModule(DFTable, 'id_table') # NB this works as expected (see textOutput in ui section above)
car_rows_selected <- callModule(DFTable, 'id_table')
observe({ updateSelectInput(session, 'car_input', selected = car_rows_selected()) })
}
shinyApp(ui = ui, server = server)
Any help would be greatly appreciated
OK, a little more trial and error got me to the right answer - the car_rows_selected item needed to be given the double arrow <<- operator in the app server function in order for it to be useable in the Car module: look for the car_rows_selected <<- callModule(DFTable, 'id_table') in the server function
library(shiny)
## prepare dataframe -----------------------------------------------------------
df <- mtcars
df$model <- rownames(df)
rownames(df) <- NULL
df <- df[1:10, c(12, 1:5)]
car_names <- data.frame(df$model)
## select module ---------------------------------------------------------------
CarInput <- function(id){
ns <- NS(id)
selectInput(ns('car_input'), 'Select car:', df$model, multiple = TRUE)
}
Car <- function(input, output, session, ...) {
observe({ updateSelectInput(session, 'car_input', selected = car_rows_selected()) })
}
## datatable module ------------------------------------------------------------
DFTableOutput <- function(id){
ns <- NS(id)
DT::dataTableOutput(ns('table'))
}
DFTable <- function(input, output, session, ...){
output$table <- DT::renderDataTable(df)
reactive(car_names[input$table_rows_selected, ])
}
## app -------------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
CarInput('id_car')
),
mainPanel(
DFTableOutput('id_table')
)
)
)
server <- function(input, output, session, ...) {
callModule(Car, 'id_car')
car_rows_selected <<- callModule(DFTable, 'id_table')
}
shinyApp(ui = ui, server = server)
I'm still getting my head around the way module namespaces work - perhaps this isn't the most "correct" approach but at least it works - happy to accept a more appropriate answer if someone posts one later

Select dataframe in Shiny

I've had some luck with Shiny and R, but I can't get an selectInput function to change the dataframe. I'm probably missing something obvious, but here's my code
require(shiny)
A <- data.frame(x=c(1,2,3),y=c(3,2,1))
B <- data.frame(x=c(1,1,5),y=c(3,5,0))
ui <- fluidPage(
selectInput("df", "Select dataframe", choices = c('A'='A','B'='B'), selected = 'A'),
plotOutput("Plot")
)
server <- function(input, output)
{
df <- reactive({
x <- as.data.frame(input$df)
})
output$Plot <- renderPlot({
df <- df()
plot(x=df$x, y=df$y)
})
}
shinyApp(ui = ui, server = server)
What am I missing?
You cant use as.data.frame and name of df
try to use get
A <- data.frame(x=c(1,2,3),y=c(3,2,1))
B <- data.frame(x=c(1,1,5),y=c(3,5,0))
shinyServer(function(input, output) {
df <- reactive({
x <- get(input$df)
})
output$Plot <- renderPlot({
df <- df()
plot(x=df$x, y=df$y)
})
})

Resources