FG74
FG74

Reputation: 61

Converting characters into variable names

exec_parties2 is a data frame withe the following 12 variables:

"CE" "DB" "ES" "FC" "FF" "HF" "HR" "JE" "JF" "JR" "SE" "SR"

I want to create a loop that ranks each variable

This is an working example for the first variable:

exec_parties2<-exec_parties2 %>% mutate(CE_T=eval(dense_rank(CE)))

I was trying something like this:

r<-colnames(exec_parties2)

i=1

for(i in r){

  exec_parties3<-exec_parties2 %>% mutate(eval(r[i])=dense_rank(desc(r[i])))   

}

Obviously, it is not working

I know this is doable and it should be documented somewhere. I just cant't find it. This is similar to a macro in SAS (a program that writes code).

Apologies for the silly question and thank you very much in advance for your help.

Upvotes: 1

Views: 212

Answers (1)

akrun
akrun

Reputation: 886938

With the current for loop, we can do an assignment (:=) within mutate by evaluating (!!) while converting the string column name to symbol (sym) and evaluate (!!)

r <- colnames(exec_parties2)
for(nm in r) {

    exec_parties2 <- exec_parties2 %>% 
                          mutate(!! nm := dense_rank(desc(!! rlang::sym(nm))))
  }  

NOTE: As in the comments, this can be done much easily with mutate_at

Upvotes: 1

Related Questions