根据两个条件筛选行

时间:2018-05-19 14:48:33

标签: dataframe

我的数据框如下所示:

Key   Year    Type
A     2000    ok
A     2001    ok
A     2001    notok
A     2002    ok
A     2003    ok
B     2000    ok
B     2001    ok
B     2001    ok
B     2002    ok
B     2003    ok
C     2000    ok
C     2001    ok
C     2002    ok
C     2003    ok

我正在寻找一个代码,如果在某一年中有两个观察结果,其中一个说" notok"和另一个" ok"在我的列类型中。 我不希望在我的新数据框中有关键b,即使一年内有2个观察结果。这是因为在我的专栏中,观察结果都标记为ok。

所以答案应该是这样的:

Key   Year    Type
A     2000    ok
A     2001    ok
A     2001    notok
A     2002    ok
A     2003    ok

这是否有一个简单的代码?

谢谢:)

2 个答案:

答案 0 :(得分:3)

使用data.table

library(data.table)
setDT(df)

# option 1
df[Key %in% df[, .SD[uniqueN(Type) == 2], by = .(Key, Year)][, unique(Key)] ]

# option 2
df[, .SD[any(.SD[, uniqueN(Type), by = Year]$V1 == 2)], by = Key]

# option 3
df[, if (any(.SD[, uniqueN(Type), by = Year]$V1 == 2)) .SD, by = Key]

给出:

   Key Year  Type
1:   A 2000    ok
2:   A 2001    ok
3:   A 2001 notok
4:   A 2002    ok
5:   A 2003    ok

dplyr

一样适用的逻辑
library(dplyr)
k <- df %>% 
  group_by(Key, Year) %>% 
  filter(n_distinct(Type) == 2) %>% 
  distinct(Key) %>% 
  pull(Key)

df %>% filter(Key %in% k )

或者用基础R:

k <- unique(df$Key[with(df, ave(Type, Key, Year, FUN = function(x) length(unique(x)))) == 2])
df[df$Key %in% k, ]

答案 1 :(得分:2)

如果这也考虑了'年'列,那么我们必须按'关键'和'年'分组

df1 %>%
   group_by(Key, Year) %>% 
   mutate(n = sum(c("ok", "notok") %in% Type)) %>% 
   group_by(Key) %>% 
   filter(any(n == 2)) %>%
   select(-n)
# A tibble: 5 x 3
# Groups:   Key [1]
#  Key    Year Type 
#  <chr> <int> <chr>
#1 A      2000 ok   
#2 A      2001 ok   
#3 A      2001 notok
#4 A      2002 ok   
#5 A      2003 ok   

或使用base R ave

i1 <- with(df1, ave(ave(Type, Key, Year, FUN = 
        function(x) length(unique(x)))==2, Key, FUN = any))
df1[i1,]
# Key Year  Type
#1   A 2000    ok
#2   A 2001    ok
#3   A 2001 notok
#4   A 2002    ok
#5   A 2003    ok

或将splittable

一起使用
subset(df1, Key %in% names(which(sapply(split(df1[-1], Key), 
     function(x) ncol(table(x))==2))))

根据预期的输出,在按“键”分组后,filter那些'Key'同时包含“ok”和“notok”%in%“Type”列

df1 %>%
  group_by(Key) %>% 
  filter(all(c("ok", "notok") %in% Type))
# A tibble: 5 x 3
# Groups:   Key [1]
#  Key    Year Type 
#  <chr> <int> <chr>
#1 A      2000 ok   
#2 A      2001 ok   
#3 A      2001 notok
#4 A      2002 ok   
#5 A      2003 ok   

如果“类型”中只有“ok”和“notok”,我们可以将唯一元素的数量计算到filter

df1 %>% 
   group_by(Key) %>%
   filter(n_distinct(Type)==2)

数据

df1 <- structure(list(Key = c("A", "A", "A", "A", "A", "B", "B", "B", 
"B", "B", "C", "C", "C", "C"), Year = c(2000L, 2001L, 2001L, 
2002L, 2003L, 2000L, 2001L, 2001L, 2002L, 2003L, 2000L, 2001L, 
2002L, 2003L), Type = c("ok", "ok", "notok", "ok", "ok", "ok", 
"ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok")), class = "data.frame", row.names = c(NA, 
-14L))