有光泽的 - 用于绘图函数的变量表达式

时间:2017-06-02 13:41:32

标签: r shiny

我是新手,我在像renderPlot这样的文档中找到了,第一个参数expr可以保存在变量中。 我很感兴趣,如果可以将文本字符串解析为表达式,然后将其传递给渲染函数。

我做了一些测试,renderPrint

code <- "x<-faithful[, 2]"
expr <- parse(text=code)
output$out1 <- renderPrint(expr)

输出显示x<-faithful[, 2],如果我用parse

包裹eval
code <- "x<-faithful[, 2]"
expr <- eval(parse(text=code))
output$out1 <- renderPrint(expr)

然后打印数据框。

如果我传递一个表达式变量,renderPlot函数对我不起作用,下面的代码将绘制一个图表

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')
})

但是,如果我从字符串解析相同的代码并保存为表达式,则它不起作用

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)
})

输出是一个空图像,我也尝试用eval包装表达式,它是相同的输出

应用链接:https://jerryjin.shinyapps.io/expr/

问题

从变量渲染表达式的正确方法是什么?

谢谢你!

1 个答案:

答案 0 :(得分:1)

你应该用eval包装表达式,它应该是大括号,因为它是一个多行表达式。

试试这个:

output$distPlot <- renderPlot({eval(expr)})