user1872443 user1872443 - 1 month ago 7
R Question

R create new column of the rank of factors

In R I have a dataframe with two columns one is a value and the other is the group that each value is assigned to:

my_group my_value
A 1.2
B 5.4
C 9.2
A 1.1
B 5.2
C 9.8
A 1.3
B 5.1
C 9.2
A 1.0
B 5.7
C 9.1


I want to create a third column that uses the average of my_value by group to rank the groups and enters that rank in each row:

my_group my_value my_group_rank
A 1.2 3
B 5.4 2
C 9.2 1
A 1.1 3
B 5.2 2
C 9.8 1
A 1.3 3
B 5.1 2
C 9.2 1
A 1.0 3
B 5.7 2
C 9.1 1

Answer

The following code will add the group ranks to your data, except that the ranks will be in opposite order, perhaps you can still use it. I use the package dplyr for this. In my example, I assume your data is in a data.frame called test.

require(dplyr)

test <- test %>% 
  group_by(my_group) %>% 
  mutate(avg = mean(my_value)) %>%
  ungroup() %>%
  mutate(my_group_rank = dense_rank(avg)) %>%
  select(-avg)


#   my_group my_value my_group_rank
#1         A      1.2             1
#2         B      5.4             2
#3         C     10.2             3
#4         A      1.1             1
#5         B      5.2             2
#6         C      9.8             3
#7         A      1.3             1
#8         B      5.1             2
#9         C      9.2             3
#10        A      1.0             1
#11        B      5.7             2
#12        C     10.1             3