R的反应性闪亮与玩具的例子

时间:2015-01-13 19:37:23

标签: r

我正在改变这个例子(https://gist.github.com/wch/5436415/)。下面是一个玩具模型。基本上我需要selectInput才能被激活,每次更改selectInput时,选择的值都会传递给global.r中的一个函数。然后我需要能够使用结果。

基本上: (1)当应用程序首次出现时应该有1个情节

(2)当用户更改滑块输入时,server.r中的max_plots函数中存在被动“input $ n”。此输入$ n将传递给global.r

中的“NumberOfPlots”函数

(3)“numberOfPlots”将返回一个数字。防爆。如果用户将select输入更改为5. 5将传递给“NumberOfPlots”,并从“NumberOfPlots”返回5

(4)现在用户做出了他的选择我在闪亮的服务器功能中使用“maxplots()”来访问图的数量

我收到错误:

Error in .getReactiveEnvironment()$currentContext() : 
  Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)

以下是我的CODE,如果您创建“runshiny.r”文件并调用以下4行,则可以运行该代码:

install.packages("shiny")
library(rJava)
library(shiny)
runApp("C://Users/me/multi")#change this to the path of your correct folder

这是我的server.r

shinyServer(function(input, output,session) {

#get the number of plots from reactive input and pass to global function
max_plots<- reactive({
  print("IN reactive function")
  NumberOfPlots(input$n)
})


  # Insert the right number of plot output objects into the web page
  output$plots <- renderUI({
    #plot_output_list <- lapply(1:input$n, function(i) {
    plot_output_list <- lapply(1:max_plots(), function(i) {
      plotname <- paste("plot", i, sep="")
      plotOutput(plotname, height = 280, width = 700)
    })
    # Convert the list to a tagList - this is necessary for the list of items
    # to display properly.
    do.call(tagList, plot_output_list)
  }) #end of output$plots

  # Call renderPlot for each one. Plots are only actually generated when they
  # are visible on the web page.
  for (i in 1:max_plots()) {
    # Need local so that each item gets its own number. Without it, the value
    # of i in the renderPlot() will be the same across all instances, because
    # of when the expression is evaluated.
    local({
      my_i <- i
      plotname <- paste("plot", my_i, sep="")

      output[[plotname]] <- renderPlot({

        plot(1:my_i, 1:my_i,
             xlim = c(1, max_plots()),
             ylim = c(1, max_plots()),
             main = paste("1:", my_i, ".  n is ", input$n, sep = "")
        )
      })#end of renderPlot
    })#end of local
  }#end of loop over max_plots

  })#end of server

这是我的global.r

NumberOfPlots<-function(n)
{
  print("in global") 
  print(n)
  length(seq(from=1 , to=n, by = 1))
}

这是我的ui.r

shinyUI(pageWithSidebar(
  headerPanel("Dynamic number of plots"),
  sidebarPanel(
    sliderInput("n", "Number of plots", value=1, min=1, max=7)
  ),
  mainPanel(
    # This is the dynamic UI for the plots
    uiOutput("plots")
  )
))

1 个答案:

答案 0 :(得分:3)

您需要将for循环包装到observe()