Home > Blockchain >  if else with filter R
if else with filter R

Time:11-05

I have a df:

df1 <- data.frame(
  sample_id = c('SB024', '3666-01', '3666-01', '3666-02'), 
  FAO = c(100,50,3,5) 

> df1
  sample_id FAO
1     SB024 100
2   3666-01  50
3   3666-01   3
4   3666-02   5

I would like to do a filter like so: If the sample id contains 3666 filter FAO >4, else filter FAO >20

So the output would be:

 sample_id FAO
1     SB024 100
2   3666-01  50
3   3666-02   5

I have tried the following after reading a previous question from here How do I filter a data frame with dplyr's filter() and R-base's ifelse()?:

df1%>% 
    filter(df1, str_detect(sample_id, "3666" & FAO >=4))

Error: Problem with filter() input ..1. i Input ..1 is case. x Input ..1$sample_id must be a logical vector, not a character.

CodePudding user response:

Your attempt was very close but there appears to be some syntax issues; this should solve your problem:

library(tidyverse)

df1 <- data.frame(
  sample_id = c('SB024', '3666-01', '3666-01', '3666-02'), 
  FAO = c(100,50,3,5)
)

df1 %>%
  filter(ifelse(str_detect(sample_id, "3666"), FAO >=4, FAO >20))
#>   sample_id FAO
#> 1     SB024 100
#> 2   3666-01  50
#> 3   3666-02   5

df1 %>%
  filter(ifelse(str_detect(sample_id, "XXXX"), FAO >=4, FAO >20))
#>   sample_id FAO
#> 1     SB024 100
#> 2   3666-01  50

Created on 2021-11-05 by the reprex package (v2.0.1)

  •  Tags:  
  • r
  • Related