2017-10-17 104 views
0

請讓我知道如何才能讓每個不同的玩家保持最高的牌? 我打算做一個for循環,但我無法弄清楚如何解決它。使用for循環來刪除R中特定實例的行

舉例來說,玩家1141剩下的唯一一排應該是23658手中的唯一一排,剩下的唯一一排1714應該是678手的那一排。

**Player PKMP ID Hands** 
    1141 PKMP002 179 
    1141 PKMP002 15 
    1141 PKMP002 22816 
    1141 PKMP002 131 
    1141 PKMP002 23658 
    1141 PKMP002 4914 
    1714 PKMP016 531 
    1714 PKMP016 91 
    1714 PKMP016 678 
    1714 PKMP016 123 
    1745 PKMP032 6821 
    1745 PKMP032 41 
    1745 PKMP032 8 
    1745 PKMP032 204 

回答

3

試試這個:

library(dplyr) 

df %>% 
    group_by(Player) %>% 
    filter(Hands == max(Hands)) 

輸出:

# A tibble: 3 x 3 
# Groups: Player [3] 
    Player `PKMP ID` Hands 
    <int> <fctr> <int> 
1 1141 PKMP002 23658 
2 1714 PKMP016 678 
3 1745 PKMP032 6821 
+0

完美地工作。非常感謝你 ! –

2

第一數據。

Lorenna <- 
structure(list(Player = c(1141L, 1141L, 1141L, 1141L, 1141L, 
1141L, 1714L, 1714L, 1714L, 1714L, 1745L, 1745L, 1745L, 1745L 
), PKMP_ID = c("PKMP002", "PKMP002", "PKMP002", "PKMP002", "PKMP002", 
"PKMP002", "PKMP016", "PKMP016", "PKMP016", "PKMP016", "PKMP032", 
"PKMP032", "PKMP032", "PKMP032"), Hands = c(179L, 15L, 22816L, 
131L, 23658L, 4914L, 531L, 91L, 678L, 123L, 6821L, 41L, 8L, 204L 
)), .Names = c("Player", "PKMP_ID", "Hands"), class = "data.frame", row.names = c(NA, 
-14L)) 

現在的代碼。我將使用sapply完成所有的工作,但隨後將結果轉置爲t()

L <- t(sapply(split(Lorenna, Lorenna$Player), function(x) x[which.max(x$Hands), ])) 
L <- as.data.frame(L) 
row.names(L) <- NULL 
L 
# Player PKMP_ID Hands 
#1 1141 PKMP002 23658 
#2 1714 PKMP016 678 
#3 1745 PKMP032 6821