Conditional filtering not working - dplyr


#1

I’m using a conditional to filter based on a string my data frame.

Here, when source is “all”, sources are not filtered as expected:

This are my original sources:

> unique(my_data$sources)
[1] "directo"        "criteo"         "adwords"        "organico"      
[5] "redes sociales" "email"          "referencias"    "onesignal"     
[9] "adsense"

However if I do filter based on some source, for example “directo”, I’m not getting “directo” as the only source in my data frame but :slight_smile:

> unique(data_a$sources)
[1] "criteo"    "onesignal"

What would you recommend to me to change in order to achieve what I need?


source <- 'directo'


if(source == 'all') {
  
  data_a <- my_data
  
} else {

  data_a <- my_data %>%
          filter(sources == as.character(source))

}

UPDATE 1:

I’ve discovered that if I groupe by only the necessary columns it filters correctly. I little bit weird. I was hoping to upload the file directly, but cannot do that. I’ll put it in Google Drive and share it.

Thank you.


#2

It would be much better to include a reprex with data reduced to the parts that produce the issue you are seeing. Even if you do upload the data you still should post a reprex.

You said it is not working “as expected”. How did it work and what specifically did you expect? The reprex is the best way to do this.

A prose description isn’t sufficient, you also need to make a simple reprex that:

  1. Builds the input data you are using.
  2. The function you are trying to write, even if it doesn’t work.
  3. Usage of the function you are trying to write, even if it doesn’t work.
  4. Builds the output data you want the function to produce.

You can learn more about reprex’s here:

Right now the is an issue with the version of reprex that is in CRAN so you should download it directly from github.

Until CRAN catches up with the latest version install reprex with

devtools::install_github("tidyverse/reprex")

We ask for a reprex because that is the quickest and easiest way for us to help you. Almost everyone here is answering questions in their spare time and anything you can do to reduce the time it takes to answer your question is appreciated.