如何删除不相似的数据框中的条目

时间:2016-05-07 19:56:29

标签: r dataframe which grepl

我有很多人的统计数据,我将其制作成data.frame teamroster。唯一的问题是,有些人有重复的名字,并且不属于名册(因为他们有不同的团队名称。请查看下面Matt Duffy中的案例teamroster)。我想系统地删除名单上没有相同团队名称的所有名称和条目。

这是我的原始data.frame:

teamroster

      Name      Team   G  PA
1  Denard Span Giants 30 135
2    Joe Panik Giants 25 107
3   Matt Duffy Giants 31 127
4   Matt Duffy Astros  3   3
5 Buster Posey Giants 27 108

解决方案代码会识别Matt Duffy位于不同的团队中,如Team列所示,并删除他,因为他在Team = Astros。这就是我希望结果数据框看起来像:

finishedteamroster

      Name      Team   G  PA
1  Denard Span Giants 30 135
2    Joe Panik Giants 25 107
3   Matt Duffy Giants 31 127
4 Buster Posey Giants 27 108

1 个答案:

答案 0 :(得分:2)

您可以将团队名称制成表格,然后取出制表的最大值。请注意,我使用which.max()来保留表名的副作用。

idx <- with(df, Team == names(which.max(table(Team))))
df[idx, ]
#           Name   Team  G  PA
# 1  Denard Span Giants 30 135
# 2    Joe Panik Giants 25 107
# 3   Matt Duffy Giants 31 127
# 5 Buster Posey Giants 27 108

数据:

df <- structure(list(Name = structure(c(2L, 3L, 4L, 4L, 1L), .Label = c("Buster Posey", 
"Denard Span", "Joe Panik", "Matt Duffy"), class = "factor"), 
    Team = structure(c(2L, 2L, 2L, 1L, 2L), .Label = c("Astros", 
    "Giants"), class = "factor"), G = c(30L, 25L, 31L, 3L, 27L
    ), PA = c(135L, 107L, 127L, 3L, 108L)), .Names = c("Name", 
"Team", "G", "PA"), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5"))