我正在尝试修复以下错误:警告:错误:请提供变量以完成
堆栈跟踪(从最里面开始)
在构建 ShinyApp 以通过条形图绘制数据时,我首先想检查 Shiny 交互是否适用于我的代码。但是,函数 complete_()
似乎不适用于 Shiny 的交互。我创建了以下 ui 和服务器来测试它:
我的数据:
gender <- c("Male", "Female")
residency <-c("InsideUS", "OutsideUS")
category <- c("A", "B")
SES <- c("Lower", "Middle", "Upper")
choices <- c("gender", "residency", "SES")
variables <- c("SES")
cat<- c("category")
df <- data.frame( gender=as.factor(sample(gender, size=100, replace=TRUE)),
residency=as.factor(sample(residency, size=100, replace=TRUE)),
category=as.factor(sample(category, size=100, replace=TRUE)),
SES=as.factor(sample(SES, size=100, replace=TRUE)))
我的用户界面:
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput(inputId = "choiceDisplay1",
label= "Please select an option",
choices= c("Gender"="gender",
"Residency"="residency",
"Social Economic Status"="SES"),
selected="gender")
),
mainPanel(
verbatimTextOutput("summary")
)
)
)
我的服务器:
server <- function(input, output) {
#Target Market
output$summary <- renderPrint({
df %>% group_by_(.choices=input$choiceDisplay1, .cat=c("category"),
.variables=c("SES")) %>%
summarize(n=n()) %>%
ungroup() %>%
complete_(.choices=input$choiceDisplay1, .cat=c("category"),
.variables=c("SES"),
fill=list(n=0)) %>%
group_by_(.choices=input$choiceDisplay1, .cat=c("category")) %>%
mutate(perc= n/sum(n))
})
}
我知道问题首先出现在 complete_()
中。对造成这种情况的原因有何见解?
谢谢!
最佳答案
该函数适用于 Shiny react 变量,但您的代码存在一些小问题。首先,当我们键入 help(complete_)
时,我们会看到 “带下划线的版本现在是多余的”
,因此我们可以使用常规版本。此外,在 complete
和随后的 group_by
语句中,我们只需要引用列,而不是
.choices=input$choiceDisplay1, .cat=c("category"), .variables=c("SES")
我们可以做到
.choices, .cat, .variables,
因为这些是我们要完成的专栏。下面给出了一个工作示例。请注意,我已将您的数据集限制为 20 条记录,因此我们实际上可以看到 complete
添加的缺失记录。
希望这对您有所帮助!
gender <- c("Male", "Female")
residency <-c("InsideUS", "OutsideUS")
category <- c("A", "B")
SES <- c("Lower", "Middle", "Upper")
choices <- c("gender", "residency", "SES")
variables <- c("SES")
cat<- c("category")
set.seed(1)
df <- data.frame( gender=as.factor(sample(gender, size=20, replace=TRUE)),
residency=as.factor(sample(residency, size=20, replace=TRUE)),
category=as.factor(sample(category, size=20, replace=TRUE)),
SES=as.factor(sample(SES, size=20, replace=TRUE)))
library(dplyr)
library(tidyr)
library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput(inputId = "choiceDisplay1",
label= "Please select an option",
choices= c("Gender"="gender",
"Residency"="residency",
"Social Economic Status"="SES"),
selected="gender")
),
mainPanel(
verbatimTextOutput("summary")
)
)
)
server <- function(input, output) {
#Target Market
output$summary <- renderPrint({
df %>% group_by_(.choices=input$choiceDisplay1, .cat=c("category"),
.variables=c("SES")) %>%
summarize(n=n()) %>%
ungroup() %>% complete(.choices, .cat, .variables,
fill=list(n=0)) %>%
group_by(.choices, .cat) %>%
mutate(perc= n/sum(n))
})
}
shinyApp(ui,server)
关于r - 来自 dplyr/tidyverse 的 Complete() 函数不适用于 Shiny 交互变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48477692/