首页 > 解决方案 > R中多列的密集排名

问题描述

如何在数据框中获得多列的密集等级?例如,

# I have:
df <- data.frame(x = c(1,1,1,1,2,2,2,3,3,3), 
                 y = c(1,2,3,4,2,2,2,1,2,3))
# I want:
res <- data.frame(x = c(1,1,1,1,2,2,2,3,3,3), 
                  y = c(1,2,3,4,2,2,2,1,2,3),
                  r = c(1,2,3,4,5,5,5,6,7,8))
res
   x y z
1  1 1 1
2  1 2 2
3  1 3 3
4  1 4 4
5  2 2 5
6  2 2 5
7  2 2 5
8  3 1 6
9  3 2 7
10 3 3 8

我的 hack 方法适用于这个特定的数据集:

df %>%
  arrange(x,y) %>%
  mutate(r = if_else(y - lag(y,default=0) == 0, 0, 1)) %>%
  mutate(r = cumsum(r))

但是必须有一个更通用的解决方案,可能使用类似dense_rank()or的函数row_number()。但我正在为此苦苦挣扎。

dplyr解决方案是理想的。

标签: rdplyr

解决方案


Right after posting, I think I found a solution here. In my case, it would be:

mutate(df, r = dense_rank(interaction(x,y,lex.order=T)))

But if you have a better solution, please share.


推荐阅读