使用for循环删除R中特定实例的行

时间:2017-10-17 21:29:58

标签: r

请您知道我怎么能为每个不同的球员保持最高牌次? 我打算做一个for循环,但我无法弄清楚如何解决它。

例如,为玩家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 

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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