Function to filter data equal to or greater than a certain value

Viewed 3249

I have a dataframe containing thousands of rows and columns. The rows contain the names of genes and the columns the names of samples.

I only want to keep the rows that contain a value equal to or greater than 5 in more than 3 samples.

I tried this so far but I can't figure out how to set multiple conditions:

data.frame1 %>% filter_all(all_vars(.>= 5))

I hope I have stated this question correctly.

2 Answers

The way I do it in my gene expression filtering pre-differential gene expression pipeline is as follows:

data.frame1[rowSums(data.frame1 >= 5) > 3, ] -> filtered.counts

And if your first column is your gene identifier, with all the other columns being numeric, you can have the evaluation skip the first column as follows:

data.frame1[rowSums(data.frame1[-1] >= 5) > 3, ] -> filtered.counts

The way to do this in dplyr 1.0.0 is

iris %>% 
    filter(rowSums(across(where(is.numeric)) > 6) > 1)

Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
1          7.6         3.0          6.6         2.1 virginica
2          7.3         2.9          6.3         1.8 virginica
3          7.2         3.6          6.1         2.5 virginica
4          7.7         3.8          6.7         2.2 virginica
5          7.7         2.6          6.9         2.3 virginica
6          7.7         2.8          6.7         2.0 virginica
7          7.4         2.8          6.1         1.9 virginica
etc

For your case

data.frame1 %>%
    filter(rowSums(across(where(is.numeric)) >= 5) > 3)

Related