1

im trying to loop mi df using a for based in a vector whit the names of the columns what i want to loop, the code is:

percep <- clv_zmvm #unique key column (CVEGEO)

#the columns from E1617_zmvm
vect_var <- c("ts18","ts19", "ts20", "ts21", "ts22", "ts23", "ts24") 

for (x in vect_var){
  v <- E1617_zmvm %>% group_by(CVEGEO) %>% filter(x>=2) %>% summarise(n())
  names(v)=c("CVEGEO", x) #rename n() column in v
  percep <- percep %>% left_join(v) #join the v result
}

The code works, the problem is all the columns have the same values and that isnt correct.

3_catsmx
  • 35
  • 5
  • 1
    Please don't post images of data; [see here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for alternatives. – alistaire May 27 '21 at 23:23
  • It would be easier to help if you create a small reproducible example along with expected output. Read about [how to give a reproducible example](http://stackoverflow.com/questions/5963269). – Ronak Shah May 28 '21 at 05:50

1 Answers1

0

The 'vect_var' are strings. We can convert to symbol and evaluate

for (x in vect_var){
  v <- E1617_zmvm %>% 
        group_by(CVEGEO) %>%
        filter(!! rlang::sym(x)>=2) %>% 
         summarise(n())
  names(v)=c("CVEGEO", x) #rename n() column in v
  percep <- percep %>% 
            left_join(v) #join the v result
 }

Or another option is across/if_any/if_all (it doesn't matter much as we are only doing one column at a time

for (x in vect_var){
  v <- E1617_zmvm %>% 
        group_by(CVEGEO) %>%
        filter(across(all_of(x), all_vars(. >=2 )) %>% 
        # or another way
        # filter(if_all(all_of(x), ~ . >= 2)) %>%
         summarise(n())
  names(v)=c("CVEGEO", x) #rename n() column in v
  percep <- percep %>% 
            left_join(v) #join the v result
 }
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks so much Akrun, the first way works perfectly. I can´t understand yet the !!rlang::sym() what i should read about that? – 3_catsmx May 29 '21 at 04:52