如果至少有一个组成员满足条件,则从data.frame中删除组

nof*_*lly 11 r subset plyr

data.frame如果他们的任何成员符合条件,我有一个我想删除整个团体的地方.

在第一个示例中,如果值是数字,则条件是NA下面的代码.

df <- structure(list(world = c(1, 2, 3, 3, 2, NA, 1, 2, 3, 2), place = c(1, 
1, 2, 2, 3, 3, 1, 2, 3, 1), group = c(1, 1, 1, 2, 2, 2, 3, 
3, 3, 3)), .Names = c("world", "place", "group"), row.names = c(NA, 
-10L), class = "data.frame")

ans <- ddply(df, . (group), summarize, code=mean(world))
ans$code[is.na(ans$code)] <- 0
ans2 <- merge(df,ans)
final.ans <- ans2[ans2$code !=0,]
Run Code Online (Sandbox Code Playgroud)

然而,这种ddply动作与NA如果条件是除"值将无法正常工作NA",或者如果值是非数字.

例如,如果我想删除任何具有世界值成员的组AF(如下面的data.frame中),那么这个ddply技巧就行不通了.

df2 <-structure(list(world = structure(c(1L, 2L, 3L, 3L, 3L, 5L, 1L, 
4L, 2L, 4L), .Label = c("AB", "AC", "AD", "AE", "AF"), class = "factor"), 
    place = c(1, 1, 2, 2, 3, 3, 1, 2, 3, 1), group = c(1, 
    1, 1, 2, 2, 2, 3, 3, 3, 3)), .Names = c("world", "place", 
"group"), row.names = c(NA, -10L), class = "data.frame")
Run Code Online (Sandbox Code Playgroud)

我可以设想一个for循环,其中为每个组检查每个成员的值,如果满足条件,则code可以填充列,然后可以基于该代码创建子集.

但是,也许有一种矢量化的方式来做到这一点?

Ste*_*pré 15

尝试

library(dplyr)
df2 %>%
  group_by(group) %>%
  filter(!any(world == "AF"))
Run Code Online (Sandbox Code Playgroud)

或者按照@akrun的说法:

setDT(df2)[, if(!any(world == "AF")) .SD, group]

要么

setDT(df2)[, if(all(world != "AF")) .SD, group]

这使:

#Source: local data frame [7 x 3]
#Groups: group
#
#  world place group
#1    AB     1     1
#2    AC     1     1
#3    AD     2     1
#4    AB     1     3
#5    AE     2     3
#6    AC     3     3
#7    AE     1     3
Run Code Online (Sandbox Code Playgroud)

  • 或者`setDT(df2)[,if(!any(world =='AF')).SD,group]`使用data.table或`setDT(df2)[,if(all(world!='AF')) ).SD,group]` (4认同)

Chr*_*ris 9

备用data.table解决方案:

setDT(df2)
df2[!(group %in% df2[world == "AF",group])]
Run Code Online (Sandbox Code Playgroud)

得到:

   world place group
1:    AB     1     1
2:    AC     1     1
3:    AD     2     1
4:    AB     1     3
5:    AE     2     3
6:    AC     3     3
7:    AE     1     3
Run Code Online (Sandbox Code Playgroud)

使用键我们可以更快一点:

setkey(df2,group) 
df2[!J((df2[world == "AF",group]))]
Run Code Online (Sandbox Code Playgroud)


mpa*_*nco 5

基础包:

df2[ df2$group != df2[ df2$world == 'AF', "group" ], ]
Run Code Online (Sandbox Code Playgroud)

输出:

   world place group
1     AB     1     1
2     AC     1     1
3     AD     2     1
7     AB     1     3
8     AE     2     3
9     AC     3     3
10    AE     1     3
Run Code Online (Sandbox Code Playgroud)

使用sqldf

library(sqldf)
sqldf("SELECT df2.world, df2.place, [group] FROM df2 
      LEFT JOIN
      (SELECT  * FROM df2 WHERE world LIKE 'AF') AS t
      USING([group])
      WHERE t.world IS NULL")
Run Code Online (Sandbox Code Playgroud)

输出:

  world place group
1    AB     1     1
2    AC     1     1
3    AD     2     1
4    AB     1     3
5    AE     2     3
6    AC     3     3
7    AE     1     3
Run Code Online (Sandbox Code Playgroud)