答案 0 :(得分:7)
有一个类似的问题,我的答案是对组和相关的排名变量进行排序,以便在使用group_by时使用row_number()。
# Sample dataset
df <- data.frame(group=rep(c("GROUP 1", "GROUP 2"),10),
value=as.integer(rnorm(20, mean=1000, sd=500)))
require(dplyr)
print.data.frame(df[0:10,])
group value
1 GROUP 1 1273
2 GROUP 2 1261
3 GROUP 1 1189
4 GROUP 2 1390
5 GROUP 1 1942
6 GROUP 2 1111
7 GROUP 1 530
8 GROUP 2 893
9 GROUP 1 997
10 GROUP 2 237
sorted <- df %>%
arrange(group, -value) %>%
group_by(group) %>%
mutate(rank=row_number())
print.data.frame(sorted)
group value rank
1 GROUP 1 1942 1
2 GROUP 1 1368 2
3 GROUP 1 1273 3
4 GROUP 1 1249 4
5 GROUP 1 1189 5
6 GROUP 1 997 6
7 GROUP 1 562 7
8 GROUP 1 535 8
9 GROUP 1 530 9
10 GROUP 1 1 10
11 GROUP 2 1472 1
12 GROUP 2 1390 2
13 GROUP 2 1281 3
14 GROUP 2 1261 4
15 GROUP 2 1111 5
16 GROUP 2 893 6
17 GROUP 2 774 7
18 GROUP 2 669 8
19 GROUP 2 631 9
20 GROUP 2 237 10
答案 1 :(得分:0)
在以下位置找到答案: Add a "rank" column to a data frame
data.selected <- transform(data.selected,
seller_feedback_score_rank = ave(seller_feedback_score, session_id,
FUN = function(x) rank(-x, ties.method = "first")))
答案 2 :(得分:0)
您可以这样做的一种方法是:
dataset<-dataset%>%arrange(ID, DateTime,Index)
dataset$Rank<-c(0,ID)[-(nrow(dataset)+1)] == ID
dataset<- dataset%>%group_by(ID)%>%mutate(Rank = cumsum(Rank))
有同样的问题!