Home > Software design >  Filtering For Specific Numbers Criteria in R DPLYR
Filtering For Specific Numbers Criteria in R DPLYR

Time:11-12

I have dataframe":

a <- data.frame(b_1=c(0.03,2.241,5.72,0.3566,1.344,2.5))

and I want to use filter like

a <- a %>% filter(b_1 %in% 0.)

so I exclude row that value not in 0,... in b_1.

But the code above was not working

The result is 0.03 and 0.3566

I have a big data, so it just an example dataframe that I want to filter. Thank you for helping

CodePudding user response:

%in% is looking for fixed match and none of the elements will satisfy that criteria. We can use substring match with str_detect

library(dplyr)
library(stringr)
a %>%
   filter(str_detect(b_1, '^0\\.'))

Or in base R

subset(a, grepl("^0\\.", b_1))

CodePudding user response:

We can try abs(b_1-0.5) < 0.5 as a condition to limit the interval to (0,1)

> subset(a, abs(b_1 - 0.5) < 0.5)
     b_1
1 0.0300
4 0.3566

CodePudding user response:

Would this work:

a %>% filter(between(b_1, -1, 1))
     b_1
1 0.0300
2 0.3566
 

CodePudding user response:

I guess you want to keep values greater than or equal to 1.If yes, then you can filter those values and save them into a new df:

b<-dplyr::filter(a,b_1 >= 1)
b
    b_1
  2.241
  5.720
  1.344
  2.500

If you want to keep values less than one:

c<-dplyr::filter(a,b_1 < 1)
c
 b_1
 0.0300
 0.3566
  • Related