簡體   English   中英

根據兩個條件過濾行

[英]Filter rows based on two criteria

我的數據框如下所示:

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”中,則可以將我所有列字母中的字母都還給我。 即使一年中有2次觀測,我也不想在新數據框中使用密鑰b。 這是因為在我的“類型”列中,觀察值都標記為“確定”。

因此答案應如下所示:

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

有一個簡單的代碼嗎?

使用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, ]

如果這還考慮了“年份”列,那么我們必須按“鍵”和“年份”分組

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 “類型”列中具有“ ok”和“ notok” %in%那些“鍵”

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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM