Aanna Aanna - 1 month ago 6
R Question

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

Answer

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