tidyverse calculate ranking per row across several columns

Viewed 326

I have the following data frame:

dat <- data.frame(id = c("a", "b", "c", "d"),
                  x1 = c(1, 3, 5, 7),
                  x2 = c(4, 2, 6, 0),
                  x3 = c(2, 2, 5, 9))

I now want to calculate the ranking per row across my three x columns and want to store that result into my dat data frame. So the result could be stored in two ways:

a) ideally, there will be 4 new columns with the respective ranks or
b) there will be a new nested column that I probably need to unnest somehow.

I tried the following which at least gives me a list column.

dat %>%
  rowwise() %>%
  mutate(my_ranks = list(rank(c_across(starts_with("x")))))

But when I try to unnest, it will give me the ranks but it does so by creating new rows (i.e. each original case now appears four times). Although I guess I could somehow reshape this result with pivot_wider, it feels wrong to follow that route.

Any better/easier idea? Thanks.

2 Answers

We can use unnest_wider

library(dplyr)
library(tidyr)
library(stringr)
dat %>%
   rowwise() %>%
   mutate(my_ranks = list(rank(c_across(starts_with("x"))))) %>%
   unnest_wider(c(my_ranks)) %>%
   rename_at(vars(starts_with("...")), ~ str_replace(., fixed("..."), "rank_x"))
# A tibble: 4 x 7
#  id       x1    x2    x3  rank_x1 rank_x2 rank_x3
#  <chr> <dbl> <dbl> <dbl>    <dbl>    <dbl>    <dbl>
#1 a         1     4     2      1        3        2  
#2 b         3     2     2      3        1.5      1.5
#3 c         5     6     5      1.5      3        1.5
#4 d         7     0     9      2        1        3  

Another option is pmap/as_tibble_row

library(tibble)
library(purrr)
dat %>% 
     mutate(my_ranks = pmap(select(., starts_with('x')), ~ 
           as_tibble_row(rank(c(...)),
            .name_repair = ~ str_c('rank', seq_along(.))))) %>%
     unnest(c(my_ranks))
# A tibble: 4 x 7
#  id       x1    x2    x3 rank1 rank2 rank3
#  <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 a         1     4     2   1     3     2  
#2 b         3     2     2   3     1.5   1.5
#3 c         5     6     5   1.5   3     1.5
#4 d         7     0     9   2     1     3  

It can be done more straightforward with rowRanks from matrixStats

library(matrixStats)
nm1 <- names(dat)[-1]
dat[paste0('rank', nm1)] <- rowRanks(as.matrix(dat[nm1]), ties.method = 'average')

I guess this is sort of tidyverse:

dat %>%
  bind_cols(as_tibble(`colnames<-`(t(apply(dat[-1], 1, rank)), paste0("rank_x", 1:3))))
#>   id x1 x2 x3 rank_x1 rank_x2 rank_x3
#> 1  a  1  4  2     1.0     3.0     2.0
#> 2  b  3  2  2     3.0     1.5     1.5
#> 3  c  5  6  5     1.5     3.0     1.5
#> 4  d  7  0  9     2.0     1.0     3.0
Related