реактивная среда в пределах реактивных значений (Ршины) - PullRequest
1 голос
/ 26 марта 2020

Я пытаюсь построить матрицу с реактивными измерениями, которую я хочу обновить с помощью выражения наблюдающего события. Моя идея заключалась в следующем:

Во-первых, я создаю объект реагирующий значения с матрицей измерений, введите $ length (-> реактивный) и введите 0. Затем я использую Наблюдение за событием с actionButton, чтобы вызвать обновление в матрица. Это влечет за собой обновление указанной c ячейки в матрице, указанной вектором реактивного индекса (ind ()), с реактивным значением (value ()).

Я понимаю проблему: внутри mat =. .. Я не могу использовать другое реактивное выражение, однако у меня нет альтернативного решения, и я был бы очень признателен за любую информацию по этому вопросу.

Заранее спасибо!

С уважением,

Джулиан


ui <- fluidPage(
  numericInput("length", "Dimensions of the matrix", value = 5),
  numericInput("a", "value for a", value = 2),
  numericInput("b", "value for b", value = 2),
  numericInput("ind1", "value for index vector 1", value = 1),
  numericInput("ind2", "value for index vector 2", value = 1),
  actionButton("go", "Update"),
  tableOutput("matrix")
)


server <- function(input, output) {

  ### Calculate the value that will be used for the update
  value <- reactive(
    mean(rbeta(100, input$a, input$b))
  )

  ### Create a reactive index vector used to determine the position of the cell in the matrix
  ind <- reactive(
    c(input$ind1, input$ind2)
  )

  ### Create reactiveValues matrix with dimensions specified in length
  beta.matrix <-  reactiveValues(
    mat = matrix(0, input$length, input$length)
  )

  ### Update matrix at positon ind with new value
  observeEvent(input$go, {
    beta.matrix$mat[ind()[1], ind()[2]] <- value() 
  }
  )

  ### Render matrix
  output$matrix <- renderTable({
    mat <- beta.matrix$mat
    mat
  })

}

# Run the application 
shinyApp(ui = ui, server = server)

1 Ответ

0 голосов
/ 26 марта 2020

Я думаю, вам понадобятся две реактивные "стадии" здесь.

  1. инициализируют пустую матрицу при изменении размеров
  2. реагируют на изменения содержимого матрицы

Пожалуйста, проверьте следующее:

library(shiny)

ui <- fluidPage(
  numericInput("length", "Dimensions of the matrix", value = 5),
  numericInput("a", "value for a", value = 2),
  numericInput("b", "value for b", value = 2),
  numericInput("ind1", "value for index vector 1", value = 1),
  numericInput("ind2", "value for index vector 2", value = 1),
  actionButton("go", "Update"),
  tableOutput("matrix")
)

server <- function(input, output) {
  ### Calculate the value that will be used for the update
  value <- reactive(mean(rbeta(100, input$a, input$b)))

  ### Create a reactive index vector used to determine the position of the cell in the matrix
  ind <- reactive(c(input$ind1, input$ind2))

  beta.matrix <- reactiveValues(mat = NULL)
  beta.matrix.ini <- reactive({
    mat = matrix(0, input$length, input$length)
  })

  observe({
    beta.matrix$mat <- beta.matrix.ini()
  })

  ### Update matrix at positon ind with new value
  observeEvent(input$go, {
    beta.matrix$mat[ind()[1], ind()[2]] <- value()
  })

  ### Render matrix
  output$matrix <- renderTable({
    mat <- beta.matrix$mat
    mat
  })

}

# Run the application
shinyApp(ui = ui, server = server)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...