根据反应性闪亮输入值和建立的数据集获取新变量(R)

问题描述 投票:0回答:1

我是 R Shiny 的新手,正在尝试根据输入值将行值附加到数据集。这是一个简化的示例版本。 用户界面让用户输入他们的邮政编码和州

 ui = fluidPage(
    titlePanel("Avg Age"),
    sidebarLayout(position = "left",
                  sidebarPanel(
                    numericInput(inputId = 'zip', label = 'Zip Code', value = NA),
                    selectInput(inputId = 'state', label = 'State', choices = c('Arkansas','Connecticut','Georgia','Illinois','Indiana','Louisiana','Maine','Maryland','Massachusetts','Michigan', 'New Hampshire', 'New Jersey', 'New York', 'Ohio', 'Oklahoma', 'Pennsylvania', 'Tennesee','Virginia', 'Vermont', 'Wisconsin')),
                    numericInput(inputId = 'height', label = 'Height', value = 54),
                    submitButton('Calculate')
                  ),
                  mainPanel(
                    textOutput("Pred")),
                  )
  )

然后服务器将使用我的全局环境中已建立的数据集来提取新变量,通过模型运行它并给出输出。

 server = function(input,output) {
    
    CL <- CL23
    
    data <- reactive({
      data.frame(
        avg_age =ifelse(CL23$State == input$state & CL23$Zip == input$zip, CL23$Age, NA),
        state = input$state,
        zip_code = input$zip,
        height_input = input$height
      )
    })
    
    pred = reactive({predict(RefreshModel,data())})
    
    output$Pred <- renderPrint(pred())

  }
  

如果用户输入邮政编码为 12345 并州为密歇根州,那么目标是什么,然后它将查看我的数据集 CL23(如下所示)并获取列中适当的年龄值。所以在这种情况下它将获取值 23。

状态 拉链 年龄
阿拉巴马州 12456 55
密歇根 12345 23
密歇根 12444 72

理想情况下,我希望数据包含所有用户输入值,但附加一行包含 CL 数据集中的年龄值。

我尝试了上面的方法,当我单击“计算”时,我的 Shiny 应用程序出现错误。我还尝试在服务器代码中使用

调用它
agepart2 <- input %>% 
        inner_join(CL, by=c("zip"="Zip","state"="State")) 

并在 data.frame 阶段调用agepart2,但在运行应用程序时也出现错误。

r shiny shiny-reactivity
1个回答
0
投票

要获取相应的年龄值,您需要过滤数据帧以查找与输入州和邮政编码匹配的行,然后提取年龄值。我已经使用

dplyr
完成了此操作,但如果您愿意,您也可以使用基本 R 来完成此操作:

server <- function(input,output) {
  
  CL <- tibble(State = c("Alabama", "Michigan", "Michigan"),
               Zip = c(12456, 12345, 12444),
               Age = c(55, 23, 72))
  
  
  data <- reactive({
    # Grabs the corresponding age value for the input state and zip values.
    # Will be NULL if there is no matching row in CL.
    corresp_age <- CL %>% 
      filter(State == input$state & Zip == input$zip) %>% 
      pull(Age)
    
    # Now we can create the dataframe, filling the age with NA if there
    # is no corresponding age.
    data.frame(
      avg_age = ifelse(is.null(corresp_age), NA, corresp_age),
      state = input$state,
      zip_code = input$zip,
      height_input = input$height
    )
  })

  # ...
}

您现在可以检查

data()
的行为是否符合我们的预期,例如通过将其渲染到 UI。

仅供参考,当在

CL23$State == input$state
的条件中包含类似
ifelse
的内容时,您将具有多个值的向量(
CL23
中的整个状态列)与单个值 (
input$state
) 进行比较,因此错误。

© www.soinside.com 2019 - 2024. All rights reserved.