使用Shiny中的if / else块进行警告处理

时间:2019-03-07 13:01:56

标签: r if-statement error-handling shiny try-catch

我正在开发一个闪亮的应用程序。它为给定的数据集选择名义(因子)和序数(数字)变量。然后将名义变量(男性,女性)转换为虚拟变量。并最终将序数变量与伪变量合并。如果同时选择名义变量和序数变量,则该应用程序运行良好。但是,如果我只想选择名义或有序变量,则会收到警告:“未找到字符或因子列。请使用select_columns选择列。”这是我的server.r和ui.R

library(fastDummies)
library(data.table)
data=data.frame(A=c(5,2,4),B=c('male','male','female'),C=c(1,3,5))
shinyServer(
function(input, output){
#Select Explanatory Nominal Variables 
output$ColumnSelector_dummy <- renderUI({
  selectInput("SelectedDummy","Select Nominal Variables (values: male,female)", 
              choices = as.list(names(data)),multiple=TRUE, selected = NULL)
})
#
df_subset_dummy <- reactive({
  a <- subset(data, select = input$SelectedDummy)
  return(a) 
})
#Convert Nominal variables to Dummy variables 
df_subset_dummy_tranformed <- reactive({
  df1 <- lapply( df_subset_dummy(), factor)
  df2 <- fastDummies::dummy_cols(df1)
  drops <- names(df1)
  df3 <- df2[, !(names(df2) %in% drops)]
  return(df3)
})
#Select Explanatory Ordinal Variables
output$ColumnSelector_ordinal<- renderUI({
  selectInput("SelectedOrdinal","Select Ordinal Variables (values: 1,2,3,4,5,6)", 
              choices = as.list(names(data)), multiple=TRUE,selected = NULL )
}) 
 df_subset_ordinal <- reactive({
  a <- subset(data, select = input$SelectedOrdinal)
  return(a) 
})  
 #Join Ordinal and Nominal dataframes   
df_nominal_ordinal_bind <- reactive({  
  df <- cbind(df_subset_dummy_tranformed(),df_subset_ordinal()) 
  return(df)
})
output$table_ordinal_nominal <- renderTable(head(df_nominal_ordinal_bind()))  
})

shinyUI(
 fluidPage(
   tabsetPanel(
     tabPanel("Data", fluid = TRUE,
            sidebarLayout(
               sidebarPanel(
               uiOutput("ColumnSelector_dummy"),  
               uiOutput("ColumnSelector_ordinal")
             ),
             mainPanel(
               tabsetPanel(
                 tabPanel('Subsets',
                          tableOutput('table_ordinal_nominal')
               ) )) ) ))))

问题:如何使用tryCatch和if / else块,以便如果df_subset_dummy_tranformed()或df_subset_ordinal()不存在,我仍然会得到df_nominal_ordinal_bind的结果,它也可以在输出$ table_ordinal_nominal中显示为表格。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

在无需过多更改代码/方法的情况下,我想您可以从对df_subset_dummy()进行检查开始:

df_subset_dummy_tranformed <- reactive({
  res <- df_subset_dummy()
  if (length(res) == 0) return(res)
  df1 <- lapply(res, factor)
  df2 <- fastDummies::dummy_cols(df1)
  drops <- names(df1)
  df3 <- df2[, !(names(df2) %in% drops)]
  return(df3)
})

至少这应该解决您提到的警告。