按组的相对顺序

  • 本文关键字:顺序 相对 r
  • 更新时间 :
  • 英文 :


我有一个看起来像的数据集

ID
1 3
1 5
1 5
1 8
1 11
1 16
2 2
2 2
2 3
2 3
2 9

使用ave+match的基本R选项

transform(
df,
Order = ave(Week,
ID,
FUN = function(x) match(x, sort(unique(x)))
)
)

ave+order(感谢@IRTFM的评论(

transform(
df,
Order = ave(Week,
ID,
FUN = order
)
)

给出

ID Week Order
1   1    3     1
2   1    5     2
3   1    5     2
4   1    8     3
5   1   11     4
6   1   16     5
7   2    2     1
8   2    2     1
9   2    3     2
10  2    3     2
11  2    9     3

带有frankdata.table选项

> setDT(df)[, Order := frank(Week, ties.method = "dense"), ID][]
ID Week Order
1:  1    3     1
2:  1    5     2
3:  1    5     2
4:  1    8     3
5:  1   11     4
6:  1   16     5
7:  2    2     1
8:  2    2     1
9:  2    3     2
10:  2    3     2
11:  2    9     3

数据

> dput(df)
structure(list(ID = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 
2L), Week = c(3L, 5L, 5L, 8L, 11L, 16L, 2L, 2L, 3L, 3L, 9L)), class = "data.frame", row.names = 
c(NA,
-11L))

您可以在dplyr:中使用dense_rank

library(dplyr)
df %>% group_by(ID) %>% mutate(Order = dense_rank(Week)) %>% ungroup
#      ID  Week Order
#   <int> <int> <int>
# 1     1     3     1
# 2     1     5     2
# 3     1     5     2
# 4     1     8     3
# 5     1    11     4
# 6     1    16     5
# 7     2     2     1
# 8     2     2     1
# 9     2     3     2
#10     2     3     2
#11     2     9     3

相关内容

最新更新