如何计算反应柱的加权百分比?

How to calculate weighted percentage for a reactive column?

我正在尝试计算某些反应性列的加权百分比。我可以使用以下代码在 R 上执行此操作:

a <- cbind(c(1, 0, 1, 0, 1), c(1, 1, 2, 2, 1), c(100, 200, 300, 50, 500))
colnames(a) <- c("gender", "race", "weights")
a <- as.data.frame(a) 
a_stack <- a %>%
  na.omit() %>%
  select(gender, race, weights) %>%
  group_by(gender, race) %>%
  summarize(totalw = sum(weights)) %>% 
  mutate(Percentage = (totalw / sum(totalw)) * 100) %>%
  arrange(gender)

这是我的输出:Output。

从上面可以看出,权重是根据gender/race累加的,得到了​​我想要的最终结果。

尽管如此,当我尝试将其转换为 R Shiny 并在反应式上下文中使用它时,我收到此错误消息 "Evaluation error: invalid 'type' (character) of argument."

这是我在 R Shiny 中使用的代码。

  completeFun <- function(data, desiredCols) {
    completeVec <- complete.cases(data[, desiredCols])
    return(data[completeVec, ])
  }
  edited_stackbar <- reactive ({
    completeFun(edited, c(input$x, input$y, input$weight)) %>%
      select_(input$x, input$y, input$weight) %>%
      group_by_(input$x, input$y) %>%
      summarize(totalw = sum(input$weight)) %>%
      mutate(Percentage = (totalw / sum(totalw)) * 100) %>%
      arrange_(input$x) %>%
      mutate(label_pos = cumsum(Percentage) - Percentage / 2,
             perc_text = paste0(round(Percentage), "%"))
  })

很难使其可重现,但我认为主要问题出在 'summarise' 部分。我不确定我是否应该使用 reactive/reactive 值函数,因为权重和变量会根据用户的输入而改变,或者我是否应该使用另一个数据集。

我将不胜感激任何帮助!谢谢。

如果 summarize 是错误的,你能试试吗?

 edited_stackbar <- reactive ({
    completeFun(edited, c(input$x, input$y, input$weight)) %>%
      select_(input$x, input$y, input$weight) %>%
      group_by_(input$x, input$y) %>%
      summarize(totalw = sum(edited$nput$weight)) %>%
      mutate(Percentage = (totalw / sum(totalw)) * 100) %>%
      arrange_(input$x) %>%
      mutate(label_pos = cumsum(Percentage) - Percentage / 2,
             perc_text = paste0(round(Percentage), "%"))
  })

 edited_stackbar <- reactive ({
    completeFun(edited, c(input$x, input$y, input$weight)) %>%
      select_(input$x, input$y, input$weight) %>%
      group_by_(input$x, input$y) %>%
      summarize(totalw = sum(get(input$weight))) %>%
      mutate(Percentage = (totalw / sum(totalw)) * 100) %>%
      arrange_(input$x) %>%
      mutate(label_pos = cumsum(Percentage) - Percentage / 2,
             perc_text = paste0(round(Percentage), "%"))
  })

无论如何,我们没有足够的信息来回答您。你可以展示一个输出(已编辑)吗?