2016-10-10 177 views
0

我有一个数据帧:过滤数据帧闪亮

height <- c('100', '101','102') 
weight <- c('40 ', '45', '58') 

df <- data.frame(height, weight) 

df  
    height weight 
1 100  40 
2 101  45 
3 102  58 

现在我想使搜索例如100和显示40,如果我SEACH 102的输出将是58。

我有以下几点:

df %>% 
    filter(height == input$counter) %>% 
    select(weight) 

这是工作,但举例来说,如果5键入任何其他数字,是不是在DF $高度,然后我得到这个:

> df %>% 
    filter(height == input$counter) %>% 
    select(weight) 
[1] weight 
<0 rows> (or 0-length row.names) 

input$counterui.R输入。结果在闪亮的作品中,但如果在高度df中找不到输入,则会显示numeric(0)。我怎样才能使它的输出是0而不是numeric(0)

回答

0

警告

我怎样才能使输出为而不是0的数字(0)

  1. 你确定你想要结果为0号吗? 请注意,如果您使用100作为过滤器值,则 df %>% filter(height == 100) %>% select(weight)的结果为data.frame。不是num
  2. 即使您使用data.frame(weight = 0)而不是0,如果您不使用options(stringsAsFactors = FALSE)作为默认值,则可能会遇到麻烦。

解决方案

我引入该功能的情况下,你会在0坚持为num中的问题要求:

zero_if_empty <- function(val){ if(dim(val)[1]==0) 0 else val }

或类似瓦尔特建议:

zeroDF_if_empty <- function(val){ if(dim(val)[1]==0) data.frame(weight = 0) else val }

在你的榜样产生的语句将被修改为:

df %>% filter(height == input$counter) %>% select(weight) %>% zeroDF_if_empty()

0

这是一个可能的解决方案:

# library 
    library(shiny) 
    library(dplyr) 
    # data frame 
    height <- c('100', '101','102') 
    weight <- c('40 ', '45', '58') 
    df <- data.frame(height, weight) 


    ui <- shinyUI(fluidPage(


     titlePanel("Filter data frame"), 


     sidebarLayout(
      sidebarPanel(
      textInput("counter", 
         "Select:" 
         ) 
     ), 


      mainPanel(
      verbatimTextOutput("selectedData") 
     ) 
     ) 
    )) 

    server <- shinyServer(function(input, output) { 

     output$selectedData <- renderPrint({ 
      if (input$counter %in% df$height) { 
        df %>% filter(height == input$counter) %>% 
       select(weight) 
      } else { 
        return(data.frame(weight = 0)); 
      } 
     }) 
    }) 


    shinyApp(ui = ui, server = server)