【问题标题】:Issue with changing a non-reactive dataframe using reactive elements使用反应性元素更改非反应性数据框的问题
【发布时间】:2021-10-20 03:06:28
【问题描述】:

我正在使用 R Shiny,这是我面临的问题:

我有一个非反应性的数据集(命名数据集)。我闪亮的应用程序的用户将输入一个值,表示将受到影响的行的百分比。

例如,如果用户输入“20”,那么我的服务器将抽取我数据集行的 20% 的样本,修改该行中的 1 列,并将此更改的行放回数据集中。

我还想最终打印原始数据集的摘要,然后打印更改数据集的摘要。

这就是我所做的(pop 是用户输入值):

#the number of rows I want to change
popint1 <- reactive({round(input$pop * 0.01 * nrow(dataset)})

#then get the summary of the original dataset
orig_summary <- reactive({dataset %>%
          group_by(age_group) %>%
          summarise(original_cvd_count = sum(as.numeric(s723d)),
                    meanSBP = mean(sb16s, na.rm = T),
                    meanDBP = mean(sb16d, na.rm = T)) %>%
          mutate(new_cvd_count = newRisk(meanSBP, meanDBP) * original_cvd_count)
      })


#then change the 'sb16s' column in a random sample of rows and put the changed rows back
env <- reactive({
        req(dataset)

        dataset[sample(nrow(dataset), popint1()), 'sb16s'] <- dataset[sample(nrow(dataset), popint1(), seed), 'sb16s'] + 5
      
})


#now get the new summary
int3_summary<- reactive({dataset %>%
        group_by(age_group) %>%
        summarise(original_cvd_count = sum(as.numeric(s723d)),
                  meanSBP = mean(sb16s, na.rm = T),
                  meanDBP = mean(sb16d, na.rm = T)) %>%
          mutate(new_cvd_count = newRisk(meanSBP, meanDBP) * original_cvd_count)
      })

output$summary1 =  renderTable({orig_summary()})
output$summary2 =  renderTable({int3_summary()})

但是我的summary1 和summary2 显示为相同(谈到meanSBP 列,它应该在summary2 中更高,因为我在行中添加了5)。我犯了什么错误,我该如何纠正?

【问题讨论】:

  • 你在用env做什么?您不会在其他任何地方引用它,它也不会以任何方式修改 dataset(即,您在其他反应中引用的 dataset)。
  • @heds1 我只使用 env 来提供反应式环境,我确实没有在其他任何地方使用它。我不知道如何使用我的反应式pop 更改我的非反应式数据集。如果您对此有任何解决方案,请告诉我。
  • orig_summary 不依赖于任何反应元素,所以你可以只做orig_summary &lt;- function() { ... }

标签: r shiny


【解决方案1】:

env 返回子集。因此,在您的反应式汇总函数中,您应该使用env 而不是dataset。给你一个想法:


summary_func <- function(df){
         df %>%
          group_by(age_group) %>%
          summarise(original_cvd_count = sum(as.numeric(s723d)),
                    meanSBP = mean(sb16s, na.rm = T),
                    meanDBP = mean(sb16d, na.rm = T)) %>%
          mutate(new_cvd_count = newRisk(meanSBP, meanDBP) * original_cvd_count)
})

env <- reactive({
        req(dataset)
        popint1 <- round(input$pop * 0.01 * nrow(dataset)
        dataset[sample(nrow(dataset), popint1), 'sb16s'] <- dataset[sample(nrow(dataset), popint1, seed), 'sb16s'] + 5        
        return(dataset)
})

int3_summary<- reactive({
        env %>%
         summary_func
})


output$summary1 =  renderTable({dataset %>% summary_func})
output$summary2 =  renderTable({int3_summary()})

我无法测试代码,因此可能存在一些错误。下次请提供一个可行的最小示例。

【讨论】:

    猜你喜欢
    • 2019-11-20
    • 1970-01-01
    • 2020-09-18
    • 2021-03-09
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多