我有一個data.table有兩個分組變量。我想計算關於組變量1的排名,同時還保留組的信息。在組內排名並在R data.table中保留ID
# require(data.table)
# require(dplyr)
set.seed(1)
DT <- data.table(group = c(rep(1,5), rep(2, 5)),
id = c(letters[1:5], letters[1:5]),
var1 = rnorm(10),
var2 = runif(10))
# > DT
# group id var1 var2
# 1: 1 a -0.6264538 0.93470523
# 2: 1 b 0.1836433 0.21214252
# 3: 1 c -0.8356286 0.65167377
# 4: 1 d 1.5952808 0.12555510
# 5: 1 e 0.3295078 0.26722067
# 6: 2 a -0.8204684 0.38611409
# 7: 2 b 0.4874291 0.01339033
# 8: 2 c 0.7383247 0.38238796
# 9: 2 d 0.5757814 0.86969085
# 10: 2 e -0.3053884 0.34034900
我可以用
DT[, lapply(.SD, function(x) percent_rank(x)),
.SDcols = c("var1", "var2"), by = .(group)]
# group var1 var2
# 1: 1 0.25 1.00
# 2: 1 0.50 0.25
# 3: 1 0.00 0.75
# 4: 1 1.00 0.00
# 5: 1 0.75 0.50
# 6: 2 0.00 0.75
# 7: 2 0.50 0.00
# 8: 2 1.00 0.50
# 9: 2 0.75 1.00
# 10: 2 0.25 0.25
計算組內的排名我也想保持id
列在新表像
# group id var1 var2
# 1: 1 A 0.25 1.00
# 2: 1 B 0.50 0.25
# 3: 1 C 0.00 0.75
# 4: 1 D 1.00 0.00
# 5: 1 E 0.75 0.50
# 6: 2 A 0.00 0.75
# 7: 2 B 0.50 0.00
# 8: 2 C 1.00 0.50
# 9: 2 D 0.75 1.00
# 10: 2 E 0.25 0.25
你可以只把'id'變量的選擇也一樣,雖然這是一個有點尷尬 - 'DT [C((ID = ID),lapply(.SD,PERCENT_RANK) ),.SDcols = c(「var1」,「var2」),by =。(group)]' – thelatemail
@thelatemail謝謝!我不知道我能做到這一點! –
或者只是給它們分配'DT [,c(「var1」,「var2」):= lapply(.SD,percent_rank),.SDcols = c(「var1」,「var2」),by = group]' –