gpt4 book ai didi

r - Shiny :使用不同的变量创建 react 过滤器。

转载 作者:行者123 更新时间:2023-12-02 17:20:42 25 4
gpt4 key购买 nike

我有一个数据框,它结合了多个网站的社会人口统计数据和意识措施。每个网站都有一个单独的栏,说明此人是否知道该网站("is"/“否”)。此外,每个受访者都应该根据他介绍的人数来加权(变量 popWeight)。

我想创建一个 Shiny 的应用程序,为知道所选网站的人显示情节。该网站应该可以通过 selectInput () 按钮进行选择。

我在 stackoverflow 上找到了几篇文章,其中介绍了使用 dplyr+shiny 的数据集过滤器。但是它们都改变了变量值而不是变量本身。

我尝试使用以下方法,但没有成功(编码示例见下文)。

[ Use shiny text input and dplyr to filter rows in a dataframe

示例数据框:

gender <- factor(sample(1:2, 5, replace=TRUE), levels = c(1,2,99), labels = c("Male", "Female", "Missing Value"))
age <- sample(18:55, 5, replace=TRUE)
web1 <- factor(sample(1:2, 5, replace=TRUE), levels = c(1,2,99), labels = c("Yes", "No", "Missing Value"))
web2 <- factor(sample(1:2, 5, replace=TRUE), levels = c(1,2,99), labels = c("Yes", "No", "Missing Value"))
web3 <- factor(sample(1:2, 5, replace=TRUE), levels = c(1,2,99), labels = c("Yes", "No", "Missing Value"))
web4 <- factor(sample(1:2, 5, replace=TRUE), levels = c(1,2,99), labels = c("Yes", "No", "Missing Value"))
web5 <- factor(sample(1:2, 5, replace=TRUE), levels = c(1,2,99), labels = c("Yes", "No", "Missing Value"))
popWeight <- sample(1000:1500, 5, replace=TRUE)

df <- data.frame(gender, age, web1, web2, web3, web4, web5, popWeight)
df

我想以交互方式做的事情:

library(ggplot2)
library(dplyr)

df1 <- filter (df, web1 == "Yes")

ggplot(df1)+
aes(x=gender, y=popWeight/sum(popWeight))+
stat_summary(fun.y = sum, geom = "bar")+
scale_y_continuous("Population (%)", labels = scales::percent)

我尝试过的

library(shiny)
library(ggplot2)
library(dplyr)

ui <- fluidPage(
selectInput(inputId = "WebsiteName", label = "Choose a Website", choices = names(df) [c(3:7)]),
plotOutput("Gender")
)


server <- function(input, output) {

dfInput <- reactive({
df %>% filter (input$WebsiteName == "Yes")
})

output$Gender <- renderPlot({
df1 <- dfInput()
ggplot(df1)+
aes(x=gender, y=popWeight/sum(popWeight))+
stat_summary(fun.y = sum, geom = "bar")+
scale_y_continuous("Population (%)", labels = scales::percent)
})
}


shinyApp(ui = ui, server = server)

有没有办法改变过滤器变量而不是值?我也愿意接受其他解决方案。

最佳答案

您可以整理您的数据集,以更有用的方式对其进行转换,从而避免让您头疼:

整洁的数据集

df<- df %>% 
gather(web, value, -age, -gender, -popWeight)

界面

更改了selectInput选项

ui <- fluidPage(
selectInput(inputId = "websiteName",
label = "Choose a Website",
choices = unique(df$web)),
plotOutput("Gender")
)

服务器

更新了 react 表达式

server <- function(input, output) {

dfInput <- reactive({
df %>% filter(web == input$websiteName & value == "Yes")
})

output$Gender <- renderPlot({
df1 <- dfInput()
ggplot(df1) +
aes(x = gender, y = popWeight / sum(popWeight)) +
stat_summary(fun.y = sum, geom = "bar") +
scale_y_continuous("Population (%)", labels = scales::percent)
})
}

关于r - Shiny :使用不同的变量创建 react 过滤器。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42957746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com