说我有以下形式的数据:
> x <- data.frame(yr = c(1,1,1,1), wk = c(1,1,2,2), id = c("a","b","a","b"), dat1 = c(3,1,10,11), dat2 = c(3,1,10,11), dat3 = c(4,2,12,8))
> x
yr wk id dat1 dat2 dat3
01 01 a 3 3 4
01 01 b 1 1 2
01 02 a 10 10 12
01 02 b 11 11 8
我想在子集rank
和yr
上返回wk
的数据框。有没有简写的方法来做到这一点?
yr wk id dat1Rnk dat2Rnk dat3Rnk
01 01 a 1 1 1
01 01 b 2 2 2
01 02 a 2 2 1
01 02 b 1 1 2
答案 0 :(得分:2)
您可以使用data.table
执行以下操作。首先定义列,然后取消列(因为按降序排列),然后重新分配列
library(data.table)
cols <- paste0("dat", 1:3)
setDT(x)[, (cols) := lapply(-.SD, frank), .SDcols = cols, by = .(yr, wk)]
x
# yr wk id dat1 dat2 dat3
# 1: 1 1 a 1 1 1
# 2: 1 1 b 2 2 2
# 3: 1 2 a 2 2 1
# 4: 1 2 b 1 1 2
或使用dplyr
library(dplyr)
x %>%
group_by(yr, wk) %>%
mutate_each(funs(rank(-.)), -id)
# Source: local data frame [4 x 6]
# Groups: yr, wk [2]
#
# yr wk id dat1 dat2 dat3
# (dbl) (dbl) (fctr) (dbl) (dbl) (dbl)
# 1 1 1 a 1 1 1
# 2 1 1 b 2 2 2
# 3 1 2 a 2 2 1
# 4 1 2 b 1 1 2