我想使用滑块上的数字输入来更改应用程序中选项的可用大小。我的所有代码都在运行,除了对top_n子组的选择不起作用。我收到错误消息:
错误:
n
必须是标量整数
我试图将input $ selected_precision转换为各种数据类型,但是没有成功。我也尝试了dplyr :: slice,但这也没有用,因为它返回了意外的结果。
所以我的问题是:如何将输入的$ selected_precision转换为标量整数?
这是我的代码(引发错误的代码在第58行中):
library(shiny)
library(plotly)
library(dplyr)
library(shinyWidgets)
groupA <- sort(rep(c('AA'),16))
groupB <- sort(rep(c('BB'),32))
group <- c(groupA, groupB)
subgroupA <- rep(c('AAA','BBB'),8)
subgroupB <- rep(c('EEE','FFF','GGG','HHH'),8)
subgroup <- c(subgroupA, subgroupB)
one <- rep(1990,4)
two <- rep(1991,4)
three <- rep(1992,4)
four <- rep(1993,4)
year <- as.character(rep(c(one,two,three,four),3))
relValue <- rnorm(48, 30, 10)
df <- data.frame(group, subgroup, year, relValue, stringsAsFactors = FALSE)
ui <- fluidPage(
sidebarPanel(
selectInput(inputId = 'selected_group', label = 'group', choices = ''),
uiOutput("selected_precision"),
pickerInput(inputId = 'selected_subgroup', label = 'subgroup', choices = '', multiple = TRUE),
verbatimTextOutput('text', placeholder = TRUE))
)
server <- function(input, output, session){
observe({
updateSelectInput(session,
'selected_group',
choices = unique(df$group))})
maxNum <- reactive({
df %>%
filter(group == input$selected_group) %>%
distinct(subgroup) %>%
summarise(n = n()) %>%
.$n})
output$selected_precision <- renderUI({
sliderInput('selected_precision', label = 'precision', min = 1, max = maxNum(),
value = maxNum(), round = TRUE, step = 1)})
filteredChoices <- eventReactive({
maxNum()
input$selected_group}, {
df %>%
filter(group == input$selected_group) %>%
group_by(subgroup) %>%
summarise(avg = mean(relValue)) %>%
arrange(desc(avg)) %>%
top_n(input$selected_precision, avg) %>% ### If you change the input$ to any integer the code will run
.[[1]]})
observeEvent({
filteredChoices
input$selected_group}, {
updatePickerInput(
session,
'selected_subgroup',
choices = filteredChoices(),
selected = filteredChoices()
)})
output$text <- renderText({input$selected_precision})
}
shinyApp(ui,server)
答案 0 :(得分:1)
filderedChoices
块第一次运行时,input$selected_precision
将是NULL
,因为在呈现相应的UI组件后输入尚未更新。
您需要处理NULL
,例如:
n <- input$selected_precision
if (is.null(n)) {
n <- maxNum()
}
然后在以后使用top_n(n, avg)
。