【问题标题】:Calculate a sum based on an input created in the same reactive function根据在同一反应函数中创建的输入计算总和
【发布时间】:2014-03-07 00:16:58
【问题描述】:

我想知道如何构建输入并在我创建它们的同一个反应函数中重用它们。

例如,在此数据框中,第一列是数字输入,最后一列应该是整行的总和。 问题是它们是在同一个反应函数中创建的,然后如果我更改输入值,反应函数将被重新执行并重新生成所有表......我试图隔离 row.sum 但它不起作用。我完全不知道该怎么做。

如果有人可以帮助我..

这是一个例子:

shiny::runApp(list(
  ui = basicPage(
    tableOutput("table")
  ),
  server = function(input, output, session) {

    output$table <- renderTable({
      mat <- matrix(c(54, 8, 26, 77, 87, 59, 92, 27, 63, 86, 18, 100, 74, 45, 46), nrow = 5, ncol = 3)
      input1 <- paste0("<input id='a", 1:nrow(mat), "' class='shiny-bound-input' type='number' value=1 style='width: 50px;'>")
      row.sum <- unlist(sapply(1:nrow(mat), function(i) input[[sprintf("a%d", i)]] + sum(mat[i,])))
      cbind(input1, mat, row.sum)
    }, sanitize.text.function = function(x) x)

  }
))

感谢您的帮助!

[请注意我unlist sapply 函数,因为第一次使用它时,尚未创建数字输入,它们都等于 NULL,然后 sapply 返回一个 numeric(0) 列表,它不能适合数据框]

【问题讨论】:

  • 这是个好主意。我对 shinyTable 包做了类似的事情。感谢分享。

标签: r shiny


【解决方案1】:

你可以试试这样的:

require(shiny)

runApp(list(
  ui = basicPage(
    tableOutput("table")
  ),
  server = function(input, output, session) {

    output$table <- renderTable({
      mat <- matrix(c(54, 8, 26, 77, 87, 59, 92, 27, 63, 86, 18, 100, 74, 45, 46), nrow = 5, ncol = 3)
      dumInput <- sapply(paste0('a', 1:5), function(x) input[[x]])
      dumInput <- ifelse(sapply(dumInput, is.null), 1, dumInput)
      input1 <- paste0("<input id='a", 1:5, "' class='shiny-bound-input' type='number' value=", dumInput, " style='width: 50px;'>" )
      row.sum <- dumInput + rowSums(mat)
      cbind(input1, mat, row.sum)
    }, sanitize.text.function = function(x) x)

  }
))

简要说明。您之前所做的是对您创建的 input[[a*]] 输入进行更改。然而 然后将输入重置为 1。上面的示例将您创建的输入中的更改传递给行总和,但也保留了更改的输入值。

另一种表述可能是使用reactiveValues 分离逻辑。这可能更可取,因为它可能更容易扩展到更复杂的示例。

shiny::runApp(list(
  ui = basicPage(
    tableOutput("table")
  ),
  server = function(input, output, session) {

    rv <- reactiveValues(
      mat = matrix(c(54, 8, 26, 77, 87, 59, 92, 27, 63, 86, 18, 100, 74, 45, 46), nrow = 5, ncol = 3)
    )

    output$table <- renderTable({
      dumInput <- sapply(paste0('a', 1:5), function(x) input[[x]])
      dumInput <- ifelse(sapply(dumInput, is.null), 1, dumInput)
      input1 <- paste0("<input id='a", 1:5, "' class='shiny-bound-input' type='number' value=", dumInput, " style='width: 50px;'>" )
      rv$rowsum <- dumInput + rowSums(rv$mat)
      cbind(input1, rv$mat, rv$rowsum)
    }, sanitize.text.function = function(x) x)

  }
))

【讨论】:

  • R shiny 不允许对反应值对象进行单括号索引,否则使用起来会更容易input[paste0('a', 1:5)]
猜你喜欢
  • 1970-01-01
  • 2023-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-04
  • 1970-01-01
  • 2022-11-24
  • 1970-01-01
相关资源
最近更新 更多