闪亮:根据用户列输入动态子集数据

Shiny: Dynamically subset data based on user column input

我有一个闪亮的应用程序,它允许用户通过从下拉列表中选择列名并为其赋值来对数据框进行子集化。在下面的代码片段中,df1 是一个数据框,如果用户从下拉列表中选择 "country" 并在文本框中输入 "UK",则临时 df,temp_dat 应该只有 UK 值.出于某种我无法理解的原因,它指出已返回 0 行 3 列。有人可以帮我吗?提前致谢。

library(shinydashboard)
ui = dashboardPage(dashboardHeader(),
                   dashboardSidebar(),
                   dashboardBody(uiOutput("subset_check1"), uiOutput("subsetbox1‌​")))

server = function(input, output, session)
{
  names = c("Jane", "Doe", "Job", "Right")
  emp_id = c(1000, 1001, 1002, 1003)
  country = c("UK", "UK", "UK", "US")
  df1 = data.frame(names, emp_id, country)
  file1_cols = colnames(df1)
  output$subset_check1 = renderUI(checkboxInput(
    "subcheck1",
    "Would you like to subset this dataset with a condition?"
  ))
  observe({
    if (!is.null(input$subcheck1))
    {
      if (input$subcheck1 == "TRUE")
      {
        #print("box was checked")
        output$subsetbox1 = renderUI(flowLayout(
          selectInput(
            "subsetbox1sel",
            "Select column:",
            choices = c(file1_cols),
            multiple = T
          ),
          textInput("subsetbox1text", "Enter value")
        ))
        observe({
          if (!is.null(input$subsetbox1sel))
          {
            if (!is.null(input$subsetbox1text))
            {
              cols_sel1 = as.character(input$subsetbox1sel)
              vals_sel1 = as.character(input$subsetbox1text)
              temp_dat = df1[df1$cols_sel1 == vals_sel1, ]
              print(temp_dat)
            }
          }
        })
      }
    }
  })
} 

目前,数据框中没有名为 cols_sel1 的列。但是您打算传递它的字符串文字值。因此,不要使用美元 $ 限定符,而是使用字符串来引用该列(即,使用下面的后者),特别是因为此 cols_sel1 随用户选择而变化:

df$col
df['col']

所以只需将您的 temp_dat 行调整为:

temp_dat = df1[df1[cols_sel1]==vals_sel1,]