【问题标题】:How to get column value from reactive function如何从反应函数中获取列值
【发布时间】:2021-08-01 12:22:07
【问题描述】:

我有 fluidRow,我在其中标记了向下框并添加了:

valueBoxOutput("income")

我还有另一个fluidRow,我在其中标记了tabPanel:

tabPanel(
   "Table",
   dataTableOutput("table") #gives me Age, Income and Occupation.

我需要根据“表格”中的用户过滤显示平均收入。数据库中的列名是:年龄、收入和工作。表格本身显示得很好。

这是我到目前为止所写的,买我的“收入”是空的,价值观没有改变。 这甚至可以从反应函数访问一列吗?如果没有,我如何访问一列来计算平均收入?

  selectedRows = reactive({
    input$table_rows_selected

  })
  
  output$income = renderValueBox({
    valueBox(
      width = 2,
      value = selectedRows()$Income %>% mean() ,
      subtitle = "Average income"
      )
  })

【问题讨论】:

  • 您能告诉我们您的table_rows_selected 输入代码是什么样的吗?了解这会产生什么价值将有助于其他人了解如何使用它来产生动态平均值。
  • 当然。我使用 renderRataTable 来获取表格: output$table = renderDataTable({ dataframe %>% select(Age, Income, Occupation) %>% datatable(options = list(paginate = F), filter = "top", colnames = c (“年龄”=“年龄”,“收入”=“收入”,“职位”=“职业”))})
  • 对,知道了。能够使用table_rows_selecteddatatable 输出的一个不明显的功能,所以这可能会在你的问题中得到澄清。不过,这应该足够了。

标签: r shiny shinydashboard


【解决方案1】:

您似乎正在使用DT::datatable() 来获取input$table_rows_selectedDT::datatable() 的文档说明如下:

selected和selectable的“indices”格式:当target为'row'或'column'时,它应该是一个普通的数字向量;当 target 为 'row+column' 时,它应该是一个列表,分别指定行和列,例如 list(rows = 1, cols = 2);当target为'cell'时,它应该是一个2-col矩阵,其中每行的两个值代表行和列索引。

这可能更清楚,但信息是如果您只选择,那么input$table_rows_selected 将给出所选行索引的数字向量。因此,您需要提取这些行,然后计算相关列的平均值,在本例中为Income。您可以使用dplyr 轻松做到这一点:

output$income = renderValueBox({

  dynamic_mean <- my_data %>%
    slice(input$table_rows_selected) %>%
    pull(Income) %>%
    mean()

  valueBox(
    width = 2,
    value = dynamic_mean,
    subtitle = "Average income"
  )
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 2017-08-26
    • 1970-01-01
    • 2011-09-10
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    相关资源
    最近更新 更多