Jib*_*ril 0 r unique data.table
SampleTable:
ID Score1 Score2
1 100 88
1 96 94
1 94 95
2 100 100
2 98 94
3 77 88
Run Code Online (Sandbox Code Playgroud)
所以我希望返回值为2,因为有2个唯一的人有一个Score1> Score2的实例.
为了再现性:
df = data.frame( ID=c(1,1,1,2,2,3), Score1=c(100,96,94,100,98,77), Score2=c(88,94,95,100,94,88) )
ID Score1 S
Run Code Online (Sandbox Code Playgroud)
我刚在想
length( unique( which( df$Score1 > df$Score2 ) ) )
Run Code Online (Sandbox Code Playgroud)
然而,返回3,显然是因为它没有考虑寻找df$ID唯一的,只是唯一出现的数量.我如何解释想要独特的唯一数量df$ID?
我想你在baseR中寻找这个:
length(unique(df$ID[df$Score1 > df$Score2]))
[1] 2
Run Code Online (Sandbox Code Playgroud)
或使用data.table:
library(data.table)
setDT(df)[Score1 > Score2, uniqueN(ID)]
Run Code Online (Sandbox Code Playgroud)
或者dplyr:
library(dplyr)
df %>% filter(Score1 > Score2) %>% { n_distinct(.$ID) }
Run Code Online (Sandbox Code Playgroud)