使ID以重复变量为条件

时间:2018-08-15 10:42:17

标签: r

我有如下数据:

enter image description here

是否有一种方法可以非常有效地(无需太多R代码)仅保留“ X”的实例等于零的“ ID”情况?例如,在这种情况下,我的数据集中仅应保留ID号3。

此问题已结束-下面的评论中有很多强烈的答案

4 个答案:

答案 0 :(得分:2)

使用data.table包,我能够快速将其组合在一起

library(data.table)
df <- data.table(ID=c(1,1,1,2,2,2,3,3,3), y=c(5,6,4,6,3,1,9,5,5), x=c(1,0,0,0,1,1,0,0,0))
df <- df[, .(ident = all(x ==0), y, x), by = ID][ident== TRUE] #aggregate, x, y and identifier by each ID
df[, ident := NULL] # get rid of redundant identifier column

答案 1 :(得分:1)

尝试: 首先获取所有ID,其中任何行的值都不为零 然后使用该子集

df <- data.frame(ID=c(1,1,1,2,2,2,3,3,3), y=c(5,6,4,6,3,1,9,5,5), x=c(1,0,0,0,1,1,0,0,0))

exclude <- subset(df, x!=0)$ID
new_df <- subset(df, ! ID %in% exclude)

答案 2 :(得分:1)

df <- data.frame(ID=c(1,1,1,2,2,2,3,3,3), y=c(5,6,4,6,3,1,9,5,5), x=c(1,0,0,0,1,1,0,0,0))
subset(df, !ID %in% subset(df, x!=0)$ID)

也就是说,首先找到x不为零(subset(df, x!=0)$ID)的ID,然后排除那些ID为(!ID %in% subset(df, x!=0)$ID)的个案

答案 3 :(得分:1)

使用ave的基本R选项,如果ID的ID值(all)为0,则选择x

df[ave(df$x == 0, df$ID, FUN = all), ]

#  ID y x
#7  3 9 0
#8  3 5 0
#9  3 5 0

等效的dplyr解决方案是

library(dplyr)
df %>%
  group_by(ID) %>%
  filter(all(x == 0)) %>%
  ungroup()

# A tibble: 3 x 3
#     ID     y     x
#  <dbl> <dbl> <dbl>
#1    3.    9.    0.
#2    3.    5.    0.
#3    3.    5.    0.