【问题标题】:shiny - expression in a variable for plot functions闪亮 - 绘图函数变量中的表达式
【发布时间】:2017-11-03 22:49:26
【问题描述】:

我是shiny的新手,我在renderPlot之类的文档中发现,第一个参数expr可以保存在变量中。 我很感兴趣是否可以将文本字符串解析为表达式,然后将其传递给渲染函数。

我做了一些测试,renderPrint:

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

输出显示x&lt;-faithful[, 2],如果我用eval 包装parse

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

服务器.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/

问题

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

谢谢!

【问题讨论】:

  • 你只解析了字符串,你没有在你的 Shiny 代码中 eval() 它。但实际上应该避免eval/parse。几乎总是有更多“R-like”的方式来做事。最好在此处描述您“真正”要解决的问题
  • @MrFlick,我知道这是个奇怪的问题,我正在尝试从文件中加载代码并动态呈现它们

标签: r shiny


【解决方案1】:

你应该用 eval 包裹表达式并且它应该用大括号括起来,因为它是一个多行表达式。

试试这个:

output$distPlot &lt;- renderPlot({eval(expr)})

【讨论】:

  • 谢谢@SBista,你拯救了我的一天,效果很好!
猜你喜欢
  • 2020-08-10
  • 2021-05-25
  • 2011-05-24
  • 1970-01-01
  • 2017-01-23
  • 1970-01-01
  • 2015-10-19
  • 2016-08-13
相关资源
最近更新 更多