1

I have a df like this :

Class_A  Class_B
   78       50
   40       60 
   30       70

The result I want is

Class_A  Class_B  RankClass_A  RankClass_B
   78       50       1            3
   40       60       2            2
   30       70       3            1

Basically, I can create two or more cols by using mutate function. However, when I put it in a loop to create more cols the code does not work.

Here is my code

label<-c('RankClass_A',"RankClass_B")
for (i in 1:2){
  for (k in 1:2){ 
    mutate(df,label[i]=dense_rank(desc(df[k])
  }
}
2
  • Thank you but I do not want to create all cols that are not relevant to the new data frame. Is there any way to select some cols by using mutate_all ? Commented Aug 13, 2018 at 3:30
  • transform(df,rank = lapply(-df,rank)) Commented Aug 13, 2018 at 3:35

1 Answer 1

4

We can use mutate_all to create the 'Rank' columns

df %>% 
    mutate_all(funs(Rank = rank(-.)))
#    Class_A Class_B Class_A_Rank Class_B_Rank
#1      78      50            1            3
#2      40      60            2            2
#3      30      70            3            1
Sign up to request clarification or add additional context in comments.

1 Comment

Maybe also add a base R option. lapply(df, function(x) rank(-x))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.