Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Looping through dataframe to filter rows

In a given dataframe, I need to filter the rows on separate columns, one at a time, using the same condition. The following formulation does not work. Any suggestions?

DF <- data.frame(A = c(1,4,99), 
                 B = c(2,5,6),
                 C = c(3,99,7))

r <- c("A", "C")

for (i in r){
  column = as.formula(paste0("DF$",i))
  DF<- DF[column != 99,]
  print(DF)
}

The desired outputs are the following two:

  A B  C
1 1 2  3
2 4 5 99

   A B C
1  1 2 3
3 99 6 7

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

We may use

library(dplyr)
library(purrr)
map(r, ~ DF %>%
      filter(!! rlang::sym(.x) != 99))

-output

[[1]]
  A B  C
1 1 2  3
2 4 5 99

[[2]]
   A B C
1  1 2 3
2 99 6 7

Or in base R

lapply(r, \(x) subset(DF, DF[[x]] != 99))
[[1]]
  A B  C
1 1 2  3
2 4 5 99

[[2]]
   A B C
1  1 2 3
3 99 6 7
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading