Reputation: 18657
I have a simple shiny app, I would like to pass the value from the selectInput
as a column name of data frame and use it in ggplot. My UI code looks like that:
library(shiny)
# Define UI for application that draws a histogram
shinyUI(fluidPage(
# Application title
titlePanel("Title"),
# Sidebar with a slider input for the number of bins
sidebarLayout(
sidebarPanel(
selectInput(inputId = "yaxis",
label = "Y-axis",
choices = list("Overall Rank" = "overall_rank",
"Income Deprivation" = "income_deprivation_rank"),
selected = "income_deprivation_rank"),
selectInput(inputId = "xaxis",
label = "X-axis",
choices = list("Overall Rank" = "overall_rank",
"Income Deprivation" = "income_deprivation_rank"),
selected = "overall_rank")),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot"),
h5("Notes"),
p("notes")
)
)
))
My server side code is vary simple, I have a SPARQL query (cut here to save the space) that creates simple data frame:
# Libs
require(shiny); require(SPARQL); require(ggplot2)
# Server function
shinyServer(function(input, output) {
# Source the data
## Define endpoint URL.
endpoint <- "http://data.opendatascotland.org/sparql.csv"
### Create Query
query.simd <- "PREFIX stats: <http://statistics.data.gov.uk/id/statistical-geography/>
(...) cut to save space (...)"
## Make the data
dta.simd<- SPARQL(url = endpoint, query = query.simd, format = "csv")$results
## Make the plot
output$distPlot <- renderPlot({
xaxis <- as.character(input$xaxis)
yaxis <- as.character(input$yaxis)
# draw the the plot
ggplot(data = dta.simd, aes(x = xaxis, y = yaxis)) +
geom_point(shape=1)
})
})
The query results in a simple data frame, resambling the extract below:
observation overall_rank income_deprivation_rank
a001 2 6
a002 10 7
a003 11 9
After compiling the app I keep on receiving the Error: object 'xaxis' not found. This leads me to believe that for whatever reason the value from the input$xaxis
is not passes to the xaxis
object and cannot be used in ggplot. If I decide to replace the as.character(input$yaxis)
with a string corresponding to the column name, like for instance overall_rank
and the other one income_deprivation_rank
the app works as it should, so the problem is clearly associated with using the input$xaxis
value. I tried the code with no as.character()
function but got the same error message.
Upvotes: 1
Views: 5513
Reputation: 111
Wherever you would normally reference the column name as a string like input$colName
, replace it with get(input$colName)
. This way Shiny knows to fetch the value of input$colName
instead of treating it as a string.
Upvotes: 3