I'm new to shiny, I found in document like renderPlot, the first parameter expr
can be saved in a variable.
I'm interested if it's possible to parse text string to an expression and then pass it to render functions.
I did some test, with renderPrint
:
code <- "x<-faithful[, 2]"
expr <- parse(text=code)
output$out1 <- renderPrint(expr)
the output is displaying x<-faithful[, 2]
, and if I wrap parse
with eval
code <- "x<-faithful[, 2]"
expr <- eval(parse(text=code))
output$out1 <- renderPrint(expr)
then it's printing the data frame.
And the renderPlot
function is not working for me if I pass an expression variable, below code will plot a histagram
output$distPlot <- renderPlot({
x <- faithful[, 2] # Old Faithful Geyser data
bins <- seq(min(x), max(x), length.out = 51)
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
However, if I parse the same code from string and save as expression, it doesn't work
ui.R
#
# This is the user-interface definition of a Shiny web application. You can
# run the application by clicking 'Run App' above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
# Define UI for application that draws a histogram
shinyUI(fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
))
server.R
#
# This is the server logic of a Shiny web application. You can run the
# application by clicking 'Run App' above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
# Define server logic required to draw a histogram
shinyServer(function(input, output) {
str<- c("x <- faithful[, 2] # Old Faithful Geyser data\n", "bins <- seq(min(x), max(x), length.out = 51)\n", "hist(x, breaks = bins, col = 'darkgray', border = 'white')")
code <- paste(str, collapse = "")
expr <- parse(text=code)
print(code)
print(expr)
output$distPlot <- renderPlot(expr)
})
the output is a empty image, I also tried wrapping expression with eval, it's the same output
app link: https://jerryjin.shinyapps.io/expr/
Question
What is the right way to render expression from variable?
thank you!