r - 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
解决方案是理想的。
解决方案
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.
推荐阅读
- algorithm - “给定一个由n个整数和一个整数b组成的数组A,找出A中是否存在两个元素c和d,使得c+d=b”
- linux - Docker 区别 docker run[...] docker container run [...]
- elasticsearch - 无法使用 ElasticSearch-PHP 更新 ES 设置
- c++ - 当 dwMessageId = 35, 37, 40... 等时,FormatMessage() 暂停程序
- c++ - _SYSTEM_PROCESS_INFORMATION 结构向后兼容
- elixir - doctest 可以解析具有默认参数的函数吗?
- python-3.x - GAE 数据存储客户端:如何对属性创建强制唯一约束
- android - Azure IOT Hub:控制连接到 IoT 中心的设备 (Android)
- shell - 如何在 unix 脚本的结果中查找字符串
- ruby-on-rails - Rails + PSQL:如何搜索具有数百万行的表