【问题标题】:Error in R shiny subsetting dataframe based on CSV file基于 CSV 文件的 R 闪亮子集数据帧中的错误
【发布时间】:2019-03-14 01:01:30
【问题描述】:

我正在使用 iris 数据集使用以下代码在 R Shiny 中创建动态更新

 write.csv(iris, file = "iris.csv", row.names = F)
# to create a local version of iris dataset

# next create UI


  ui <- fluidPage(


   fileInput("file", "Browse",
        accept = c("text/csv",
                   "text/comma-separated-values,text/plain",
                   ".csv")
    ),
   selectInput(inputId = "Speciesname", label = "Name",choices = 
    NULL,selected = NULL),
   tableOutput("data")
   )


   #Create server
    server <- function(input, output,session) {



 df = reactive({
 req(input$file)
 return(read.csv(input$file$datapath))
 })

  observe({
  choices1 = unique(df()$Species)
  updateSelectInput(session,"Speciesname", choices =  choices1)
  })
  output$data <- renderTable({
  req(input$Speciesname)
  df[as.character(input$Speciesname), ]
  }, )
   }


 #Run app
 shinyApp(ui, server)

我能够读取文件。但是子集显示以下错误和闪亮的应用程序

 Warning: Error in [: object of type 'closure' is not subsettable
 [No stack trace available]

我无法理解或解决此错误。当我不使用数据集的本地副本但使用内置的 R iris 数据集时,代码运行。我请求有人在这里指导我

【问题讨论】:

  • 应该是df(),如df()[as.character(input$Speciesname), ]
  • 谢谢先生。我已经进行了更正,但现在我只在输出的所有行中获得 NA 值。出现列标题

标签: r csv shiny subset


【解决方案1】:

这应该可以完成工作

library(shiny)
write.csv(iris, file = "iris.csv", row.names = F)
# to create a local version of iris dataset

# next create UI

ui <- fluidPage(


  fileInput("file", "Browse",
            accept = c("text/csv",
                       "text/comma-separated-values,text/plain",
                       ".csv")),
  selectInput(inputId = "Speciesname", label = "Name",choices = 
                NULL,selected = NULL),
  tableOutput("data")
)


#Create server
server <- function(input, output,session) {

  df = reactive({
    req(input$file)
    return(read.csv(input$file$datapath))
  })

  observe({
    choices1 = unique(df()$Species)
    updateSelectInput(session,"Speciesname", choices =  choices1)
  })

  output$data <- renderTable({
    req(input$Speciesname)
    df()[df()$Species %in% input$Speciesname,]
  })
}


#Run app
shinyApp(ui, server)

【讨论】:

  • 谢谢先生。 %in% 运算符是否必不可少
  • 是的,它是== 的更好版本,它会处理多个匹配项,如果有的话。例如,如果您选择了 2 个物种并希望显示它们,则使用此运算符更容易,而不是写两次 ==
  • 可爱。谢谢楼主
猜你喜欢
  • 2018-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-07
  • 2014-02-26
  • 2021-07-08
  • 2021-06-02
相关资源
最近更新 更多