Я изменяю этот пример (https://gist.github.com/wch/5436415/). Ниже представлена игрушечная модель. Bascially мне нужно, чтобы selectInput был реактивным, и каждый раз, когда selectInput изменяется, выбранное значение переходит к функции в global.r. Тогда мне нужно будет использовать результат.Реактивность в R-блестящей с игрушечным примером
В основном: (1) При первом появлении приложения должен быть 1 участок
(2) Когда пользователь изменяет входной ползунок есть реактивный «вход $ п» в функции max_plots в сервере. р. Этот вход $ n передается функции «NumberOfPlots» в global.r
(3) «numberOfPlots» вернет число. Ex. Если пользователь меняет вход выбора на 5. 5 передается в «NumberOfPlots», а 5 возвращается из «NumberOfPlots»
(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.)
ниже приведен код, который вы можете запустить, если вы создаете файл «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")
)
))
Вы проверили это? Я думаю, что может потребоваться «реактивный», но я не уверен, что все «plotOutputs» будут работать. –
Да, я убедился, что это работает. Это действительно хорошая программа: цикл 'for' генерирует экземпляры' n' plot 'output', а' output $ plots' возвращает список этих экземпляров. В результате код генерирует страницу с динамическим числом графиков. Единственным недостающим элементом было «наблюдать()». –
Спасибо, хорошо учиться. –