Fail to use for loop when var is in group_by

Here are the code I wanted to execute:

feature_risk_col <-
  loan_data %>% 
  select(!where(is.numeric)) %>% names()
for(i in feature_risk_col){
f_risk <-
  loan_data %>% 
  group_by(i) %>% 
  summarize(rate = mean(risky_loan), count = n()) %>% 
  ungroup() %>% 
  mutate(diff = rate - g_risk,
         risk = rate / g_risk)

  paste("Feature Risk of", i)
  print(f_risk)
  print(" ")
}

The column names from feature_risk_col doesn't copied into the group_by() function when the for loop runs. Instead it asks for column named i (Column i is not found).

Is this kind of problem better done using apply family function rather than for loop? Why? If so, I'm not sure how, should I create a function to be used in the apply family function?

I tried to make function and apply it in sapply, but the group_by() still asks for column named i. So I guess it's not the for loop that causes the error.

Oops. Never mind.

I solved it with:

group_by(loan_data[i])

This topic was automatically closed 7 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.