Filter with loop

I'm using the filter function within the loop
In df, there are columns :
c_num_hh, c_num_hh_Max,

These columns of df are only for examples, there are a lot of columns - similar to these examples.
I want to filter like c_num_hh>c_num_hh_Max, and so on. So I try the coding below within loop, it doesn't work.

r<-list("c_num_hh" , "ib2a_anctime")
for(i in seq_along(r)){

However, I did the following, it works


Indeed, I need to use the filter with loop because there are a lot of columns (_,Max, _ _ _ _ )
Please suggest to me!!

Notice that in this call to filter


you are using the symbols c_num_hh and c_num_hh_Max. Inside of the loop, you are using the character values "c_num_hh" and "c_num_hh_Max". You can change the characters into symbols with the sym() function from rlang. I admit that I never use these rlang functions and I do not understand them very well.

library(dplyr,warn.conflicts = FALSE)

DF <- data.frame(AB = c(5,7,3,5,1,4,8), AB_Max = 5, 
                 CD = c(16,12,17,14,19,10,14),CD_Max = 14)
r <- list("AB", "CD")

for(i in seq_along(r)){
  assign(paste0("d",i),filter(DF,!!sym(r[[i]]) > !!sym(paste0(r[[i]],"_Max"))))

#>   AB AB_Max CD CD_Max
#> 1  7      5 12     14
#> 2  8      5 14     14

Created on 2020-11-16 by the reprex package (v0.3.0)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.