简体   繁体   中英

Filter dataframe in R Shiny

I have a dataframe:

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

Now I want to make to search for example 100 and be shown 40, and if I seach 102 the output would be 58.

I have the following:

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

Which is working, but If type in for example 5 any other number that isn't in the df$height then I get this:

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

The input$counter is a ui.R input. The result in shiny works, but if the input is not found in the height df then it will show numeric(0) . How can I make it that the output is 0 instead of numeric(0) ?

This is a possible solution:

    # 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)

Warning :

How can I make it that the output is 0 instead of numeric(0)

  1. Are you sure you want the result as 0 num? Please keep in mind that in case you use 100 as a filter value the result of the df %>% filter(height == 100) %>% select(weight) is a data.frame . Not num .
  2. Even if you use data.frame(weight = 0) instead of 0 you might get into a trouble in case you don't use options(stringsAsFactors = FALSE) as default.

Solution :

I'd introduce the function in case you'd insist on 0 as num as requested in the question:

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

or similar to Valter suggestion:

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

The resulting statement in your example would be altered as:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM