0

I am using R Markdown to create a dashboard, as it is easier for me than using R-Shiny. I have a piece of code that stopped working after I upgraded tidyverse. Tidyverse has changed the behavior of its str_detect() string manipulation in that it now throws an error if an empty string is detected. So, I need some suggestions. Below is the code and what I need to do (focus on the str_detect() part).

df %>%
  select(YEAR,
         Q...) %>%
  filter(
    !is.na(HAILWT) &
    CODMSIZE >= input$codmeshTBL[1] & CODMSIZE <= input$codmeshTBL[2] &
    YEAR >= 
... &
    str_detect(CATDISP, if_else(input$dispositionTBL == "All", "", input$dispositionTBL)) 
... &
  ) %>%
...

The input$dispositionTBL is a dropdown control with options "All", "Discarded", "Kept", and "Unknown" as options. The "discarded", "kept", and "unknown" are rows of the CATDISP column in the dataframe. The "All" I added to the control. When the user selects "All", there should be no filtering on the column 'CATDISP'. When the user selects anything else, filtering should occur on the selected option. This all worked fine before the update, but now throws the error "str_detect():! pattern can't be the empty string ("").". This is b/c of the empty string from the 'All' selection. So, I tried to add NULL, True, and c("Discarded", "Kept", "Unknown") to no avail. Anyone out there has a strategy/suggestion on how I can disable filtering upon the user selecting 'All' for that particular column? Thx a lot.

Ralf Riedel
  • 479
  • 4
  • 4
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Feb 03 '23 at 20:49
  • BTW, the solution you provided I tried at some point. The error I got was this: "Error in filter: Problem while computing `..1 = ... & ...`. Caused by error in `if_else()`: ! `false` must be length 1 (length of `condition`), not 326135.", if that means anything to you. Is this b/c the if statement is expecting FALSE, instead of a lengthy string? If so, what's the workaround? – Ralf Riedel Feb 05 '23 at 13:37
  • Got it resolved. I used case_when(), instead of if_else(). if_else() seems to be too restrictive. Thank you so much for all the assistance. Have a great day. – Ralf Riedel Feb 05 '23 at 15:20

1 Answers1

0

It would be easier, if you state what you desired output looks like.

My understandings is that you want to return TRUE if the user input is "All", and for any other case you want to return str_detect(CATDSIP, input$dispositionTBL). In that case just replace the str_detect call with :

if_else(
  input$dispositionTBL == "All",
  TRUE, # this is basically what `grepl("",input$dispositionTBL) would return
  stringr::str_detect(CATDISP, input$dispositionTBL)
  ) 
TimTeaFan
  • 17,549
  • 4
  • 18
  • 39