How can i get all the results with different filter criteria using dplyr or loop in R?

Viewed 38

I have come up with a question when I trying to get all the output data.frame under different filter criteria (by using dplyr::filter method) using R. Here is my data for illustrating:

df <- tibble(a = rnorm(10),b = rnorm(10),c = rnorm(10))

as you can see, df has 3 columns. I want to put different filter method on each column and get all the results of the number of row. For example,

df_number1 <- df %>% filter(a > 0.2, b >0.7, c>=0.5) %>% nrow()

I also want to know

df_number2 <- df %>% filter(a > 0.2, b >0.7, c<0.5) %>% nrow()

So there are 2^3 = 8 kinds of different situations, how can I get the results at once? Thank you for your help!

1 Answers

First we can use some ifelse statements to create some descriptive strings specifying the condition, this is only for better descriptions in the output. Then use table to "count" the occurrence of each string. Finally, change the table output to a dataframe for better visualisation.

In this way, you can see a complete picture of counts with different condition combinations.

library(dplyr)

set.seed(12)
df <- tibble(a = rnorm(10),b = rnorm(10),c = rnorm(10))

df %>% mutate(a = ifelse(a > 0.2, "a > 0.2", "a <= 0.2"),
              b = ifelse(b > 0.7, "b > 0.7", "b <= 0.7"),
              c = ifelse(c >= 0.5, "c >= 0.5", "c < 0.5")) %>% 
  table() %>% 
  as.data.frame()

        a        b        c Freq
1 a <= 0.2 b <= 0.7  c < 0.5    6
2  a > 0.2 b <= 0.7  c < 0.5    1
3 a <= 0.2  b > 0.7  c < 0.5    1
4  a > 0.2  b > 0.7  c < 0.5    0
5 a <= 0.2 b <= 0.7 c >= 0.5    1
6  a > 0.2 b <= 0.7 c >= 0.5    1
7 a <= 0.2  b > 0.7 c >= 0.5    0
8  a > 0.2  b > 0.7 c >= 0.5    0

Data

df <- structure(list(a = c(-1.48056759491936, 1.57716947155863, -0.956744479084269, 
-0.920005247558641, -1.99764209693134, -0.27229604424923, -0.315348711467784, 
-0.628255236517538, -0.106463884872094, 0.428014802202354), b = c(-0.777719582147445, 
-1.29388229761362, -0.779566508059429, 0.0119517585652984, -0.152416237822168, 
-0.703464254478642, 1.18887915627567, 0.340512270849188, 0.506968172259166, 
-0.293305149081411), c = c(0.223641415376273, 2.00720145694544, 
1.01197911806715, -0.302459245168265, -1.02524483901366, -0.267384829994282, 
-0.199105661114762, 0.131122595424375, 0.145799895543701, 0.362064721117229
)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-10L))
Related