Home > Blockchain >  How to apply a filter ( dplyr) in ggplot2?
How to apply a filter ( dplyr) in ggplot2?

Time:02-05

I'm trying to fill some specific areas of my geographic map with the purple color and I have no problem in doing that. This is the script I'm using:

right_join(prov2022, database, by = "COD_PROV") %>% 
  ggplot(aes(fill = `wage` > 500 & `wage` <=1000)) 
  geom_sf()  
  theme_void()  
  theme(legend.title=element_blank()) 
  scale_fill_manual(values = c('white', 'purple'))

But now I want to apply a filter in my ggplot2 picture. I need to fill the areas of the map, but only those that have the value 13 in the column(variable) COD_REG. I have added filter( COD_REG == 13) but it doesn't work

right_join(prov2022, database, by = "COD_PROV") %>% 
  filter( COD_REG == 13)
  ggplot(aes(fill = `wage` > 500 & `wage` <=1000)) 
  geom_sf()  
  theme_void()  
  theme(legend.title=element_blank()) 
  scale_fill_manual(values = c('white', 'purple'))

R answers

> right_join(prov2022, database, by = "COD_PROV") %>% 
    filter( COD_REG == 13)
Error in `stopifnot()`:
! Problem while computing `..1 = COD_REG == 13`.
✖ Input `..1` must be of size 106 or 1, not size 107.
Run `rlang::last_error()` to see where the error occurred.

My database has 106 obs and 13 variables and it is like this

COD_REG   COD_PROV   wage
1         91         530
1         92         520
1         93         510
2         97         500
2         98         505
2         99         501
13        102        700
13        103        800   
13        109        900

Where is the mistake? Why R answers << ✖ Input ..1 must be of size 106 or 1, not size 107. >> ?? How can I solve???

CodePudding user response:

I think you might have another filter function that shadows the dplyr one. Also you have forgot to add a %>% after your filter. Could you try this:

right_join(prov2022, database, by = "COD_PROV") %>% 
  dplyr::filter(COD_REG == 13) %>%
  ggplot(aes(fill = `wage` > 500 & `wage` <=1000)) 
  geom_sf()  
  theme_void()  
  theme(legend.title=element_blank()) 
  scale_fill_manual(values = c('white', 'purple'))

The code runs as expected with the sample data.

library(tidyverse)

data <- "COD_REG   COD_PROV   wage
1         91         530
1         92         520
1         93         510
2         97         500
2         98         505
2         99         501
13        102        700
13        103        800
13        109        900"

read_table(data) |> 
  filter(COD_REG == 13)
#> # A tibble: 3 × 3
#>   COD_REG COD_PROV  wage
#>     <dbl>    <dbl> <dbl>
#> 1      13      102   700
#> 2      13      103   800
#> 3      13      109   900

Created on 2023-02-03 with reprex v2.0.2

  • Related