gpt4 book ai didi

R 中的 react 性与玩具示例 Shiny

转载 作者:行者123 更新时间:2023-12-01 02:12:44 24 4
gpt4 key购买 nike

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

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

(2) 当用户更改 slider 输入时,server.r 中的 max_plots 函数中有一个响应式“input$n”。这个 input$n 被传递给 global.r 中的“NumberOfPlots”函数

(3) "numberOfPlots"将返回一个数字。前任。如果用户将选择输入更改为 5。5 被传递给“NumberOfPlots”,而 5 从“NumberOfPlots”返回

(4) 既然用户做出了选择,我在 Shiny 的服务器函数中使用“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.)

下面是我的代码,如果你创建一个“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")
)
))

最佳答案

你需要结束你的for循环到 observe() .

关于R 中的 react 性与玩具示例 Shiny ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27930144/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com