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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.