2016-10-10 174 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)