简体   繁体   English

在 R Shiny 中添加和选择 dataframe 列

[英]Adding and selecting dataframe columns in R Shiny

I'm working on an R Shiny App that plots monthly percent changes in political party registrations.我正在开发一个 R Shiny 应用程序,该应用程序绘制政党登记的每月百分比变化。 I'm still pretty new to interactive web apps (and Stack Overflow), and just haven't been able to find answers to these quesions -- thanks/sorry in advance.我对交互式 web 应用程序(和 Stack Overflow)仍然很陌生,只是无法找到这些问题的答案——提前谢谢/抱歉。

In an older version of the app ( here ) I was able to let the user select the region, and I had manually put % monthly changes directly in the original dataframe.在旧版本的应用程序(此处)中,我能够让用户 select 区域,我已经手动将 % 每月更改直接放在原始 dataframe 中。

What I'm trying to do now is enable the app to:我现在要做的是使应用程序能够:

  1. Allow the user to choose/input a specific political party, which are each stored as columns in my df允许用户选择/输入一个特定的政党,每个政党都存储为我的 df 中的列
  2. Then have the app itself calculate and add a new column with % monthly change for the selected party & region, so I don't have to do that manually for each party in the original df.然后让应用程序本身计算并添加一个新列,其中包含所选政党和地区的每月变化百分比,因此我不必为原始 df 中的每一方手动执行此操作。

I can't figure out how to let the user select by party name / df column.我不知道如何让用户 select 按派对名称/df 列。 I've tried:我试过了:

selectizeInput(inputId = 'Party', label= 'Party',
                             choices = colnames(df_2016)

but that doesn't work.但这不起作用。

I also have no clue how to do 2 lol.我也不知道怎么做2大声笑。

Thanks in advance for any help you can provide;提前感谢您提供的任何帮助; would realy appreciate if anyone could point me in the right direction or toward resources to learn how to do this.如果有人能指出我正确的方向或资源来学习如何做到这一点,我将不胜感激。 The relevant files are here if needed.如果需要,相关文件在这里

Here's the code for my UI and Server:这是我的 UI 和服务器的代码:

UI:用户界面:

library(shiny)
library(shinydashboard)
library(ggplot2)
library(dplyr)
library(ggthemes)
library(shinythemes)
library(lubridate)

df_2016 = read.csv('df_2016.csv')
df_2020 = read.csv('df_2020.csv')

# Define UI for application
fluidPage(theme = shinytheme('cerulean'),
          
          # Application title
          titlePanel("NJ Voter Registration"),
          
          sidebarLayout(
              # Drop-down menu with region options
              
              mainPanel(
                  selectizeInput(inputId = 'County', label= 'Region',
                                 choices = df_2016$County),
            
              ),
              
              mainPanel(
                  tabsetPanel(
                      
                      tabPanel('Home',
                               "Data is sourced from the NJ Division of Elections Voter Registration Statistics Archive, which can be accessed at https://www.state.nj.us/state/elections/election-information-svrs.shtml",
                               "Please use the drop-down menu above to select whether to view statewide statistics, or data for a specific county.",
                      ),
                      
                      tabPanel('2016 Data',
                               'The dataframe for your selection is provided here.',
                               tableOutput('tableonesix')
                      ),

                      tabPanel('2020 Data',
                               'The dataframe for your selection is provided here.',
                               tableOutput('tabletwozero')
                      )
                      
                  )
              )
          )
          
)

Server:服务器:

library(shiny)
library(shinydashboard)
library(ggplot2)
library(dplyr)
library(ggthemes)
library(shinythemes)
library(lubridate)

df_2016 = read.csv('df_2016.csv')
df_2020 = read.csv('df_2020.csv')


function(input, output) {
    
    output$tableonesix=renderTable(
        df_2016 %>%
            filter(County==input$County)
    )
    
    output$tabletwozero=renderTable(
        df_2020 %>%
            filter(County==input$County)
    )
    
}

This sample app shows how it can be done.这个示例应用程序展示了它是如何完成的。

  • Your idea using selecizeInput was correct.您使用selecizeInput的想法是正确的。 However, I would not recommend declaring the data frames as global variables.但是,我不建议将数据框声明为全局变量。 The usual approach would be to keep the data in the server and feed only the data we want to show to the client.通常的方法是将数据保存在服务器中,只提供我们想要显示给客户端的数据。
  • Use updateSelectizeInput to set the choices once the data frames have been loaded.加载数据框后,使用updateSelectizeInput设置选项。 The observer will do that every time df changes.每次df更改时, observer都会这样做。
  • Finally, renderTable filters the relevant part of the data frame and sends it to the client.最后, renderTable过滤数据帧的相关部分并将其发送给客户端。
library(shiny)

ui <- fluidPage(
    titlePanel("Party Sample"),

    sidebarLayout(
        sidebarPanel(
            selectizeInput("Party", "Party", choices = NULL),
            selectizeInput("County", label= "Region", choices = NULL),
        ),

        mainPanel(
           tableOutput("tableonesix")
        )
    )
)

# 
server <- function(input, output, session) {
  # DUMMY DATA
  df <- reactiveVal(data.frame(Democrats = 1:10, Republicans = 10:1, 
                               Libertarians = 1:10, GreenParty = 10:1,
                               County = sample(c("A", "B", "C"), 10, TRUE)))

  observe({
    # select only the party columns 1-4; 5 is the county column
    updateSelectizeInput(session, "Party", choices = colnames(df()[1:4])) 
    # Get counties without duplicates
    updateSelectizeInput(session, "County", choices = unique(df()$County))
  })
  
  output$tableonesix <- renderTable({
    # Do not run unless selects have a usable value
    req(input$Party, input$County)
    # Select: here in base R (not dplyr)
    df()[df()$County == input$County, input$Party]
  })
  
}

# Run the application 
shinyApp(ui = ui, server = server)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM