【发布时间】:2022-01-23 17:34:13
【问题描述】:
下面的代码在没有 Shiny 的情况下运行,可以很好地通过 2 种不同的测量时间范围的方法(按日历月(“Period_1”)和自元素起源以来经过的月份(“Period_2”))对数据进行分组,并用于扩展按 Period_2 分组时将数据框用于校正周期:
library(tidyverse)
data <- data.frame(
ID = c(1,1,2,2,2,2),
Period_1 = c("2020-03", "2020-04", "2020-01", "2020-02", "2020-03", "2020-04"),
Period_2 = c(1, 2, 1, 2, 3, 4),
ColA = c(10, 20, 30, 40, 50, 52),
ColB = c(15, 25, 35, 45, 55, 87)
)
### Expand the dataframe to including missing rows ###
dataExpand <-
data %>%
tidyr::complete(ID, nesting(Period_2)) %>%
tidyr::fill(ColA, ColB, .direction = "down")
### Run the expanded data frame through grouping code ###
# Group by calendar month (Period_1)
groupData_1 <-
dataExpand %>%
group_by(Period_1) %>%
select("ColA","ColB") %>%
summarise(across(everything(), sum)) %>%
filter(!is.na(Period_1)) # << Add this code to delete NA row for calendar period
# Group by vintage month (Period_2)
groupData_2 <-
dataExpand %>%
group_by(Period_2) %>%
select("ColA","ColB") %>%
summarise(across(everything(), sum, na.rm = TRUE))
结果(运行上述代码时正确):
> groupData_1
# A tibble: 4 x 3
Period_1 ColA ColB
<chr> <dbl> <dbl>
1 2020-01 30 35
2 2020-02 40 45
3 2020-03 60 70
4 2020-04 72 112
> groupData_2
# A tibble: 4 x 3
Period_2 ColA ColB
<dbl> <dbl> <dbl>
1 1 40 50
2 2 60 70
3 3 70 80
4 4 72 112
但是,当我将上述内容放入 Shiny 时,用户可以单击单选按钮选择按 Period_1 或 Period_2 分组,应用程序崩溃。问题似乎出在if(input$grouping == 'Period_1'... 行中,因为当我将其注释掉时,应用程序会运行(但没有像这条线那样删除不适用的 Period_1)。如何解决这个问题?
library(shiny)
library(tidyverse)
ui <-
fluidPage(
h3("Data table:"),
tableOutput("data"),
h3("Sum the data table columns:"),
radioButtons(
inputId = "grouping",
label = NULL,
choiceNames = c("By period 1", "By period 2"),
choiceValues = c("Period_1", "Period_2"),
selected = "Period_1",
inline = TRUE
),
tableOutput("sums")
)
server <- function(input, output, session) {
data <- reactive({
data.frame(
ID = c(1,1,2,2,2,2),
Period_1 = c("2020-03", "2020-04", "2020-01", "2020-02", "2020-03", "2020-04"),
Period_2 = c(1, 2, 1, 2, 3, 4),
ColA = c(10, 20, 30, 40, 50, 52),
ColB = c(15, 25, 35, 45, 55, 87)
)
})
dataExpand <- reactive({
data() %>%
tidyr::complete(ID, nesting(Period_2)) %>%
tidyr::fill(ColA, ColB, .direction = "down")
})
summed_data <- reactive({
dataExpand() %>%
group_by(!!sym(input$grouping)) %>%
select("ColA","ColB") %>%
summarise(across(everything(), sum, na.rm = TRUE)) #%>%
# Below removes Period_1 rows that are added due to Period_2 < 4 when grouping by Period_2
if(input$grouping == 'Period_1'){filter(!is.na(Period_1))}
})
output$data <- renderTable(data())
output$sums <- renderTable(summed_data())
}
shinyApp(ui, server)
【问题讨论】:
-
OP,这可能是掩蔽问题吗?我发现当我加载一些包时,
dplyr::filter()显然被其他包所掩盖。因此,每当我使用filter()时,我都会从dplyr显式调用该函数。如果你这样做,你还会遇到同样的问题吗?换句话说,试试:if(input$grouping == 'Period_1'){dplyr::filter(!is.na(Period_1))} -
chemdork123,在这种情况下不能解决问题。但是,当将来遇到问题时,我会记住这个可能的解决方案。我没有考虑掩蔽问题。
标签: r dplyr filter shiny conditional-statements