簡體   English   中英

使用 case_when() 和 filter() 根據 R 中一列中的值和另一列中的級別對數​​據框進行子集化

[英]using case_when() and filter() to subset a dataframe based on values in one column and levels in another column in R

我想根據一列中的值過濾(從中提取行)數據幀,同時確保所有與我提取的行具有相同級別的行也被提取。 例子:

condition<- rep(c("c1", "c2", "c3", "c4"), times = 4)
levelled <- c(rep("a",times = 4), rep("b", times = 4), rep("c", times = 4), rep("d", times = 4))
direction <- c(rep("up", times=10), rep("down", times = 1), rep("up", times = 5))

df <- data.frame(condition, levelled, direction)

這導致此數據框:

   condition levelled direction
1         c1        a        up
2         c2        a        up
3         c3        a        up
4         c4        a        up
5         c1        b        up
6         c2        b        up
7         c3        b        up
8         c4        b        up
9         c1        c        up
10        c2        c        up
11        c3        c      down
12        c4        c        up
13        c1        d        up
14        c2        d        up
15        c3        d        up
16        c4        d        up

我只關心direction == "down" ,但我想提取具有在同級別的所有行levelled列。 所以我想要的輸出 df 是這樣的:

desired_output 
   condition levelled direction
9         c1        c        up
10        c2        c        up
11        c3        c      down
12        c4        c        up

在我的desired_output數據desired_output ,我提取了direction == down行,以及在levelled列中具有相同級別的其他 3 行。 我想我應該嘗試這樣的事情,但我不知道在波浪號的右側寫什么:

desired_output <- df %>% fiter(
  case_when(
    direction == "up" ~ #??
  )
)

你想要這樣的東西嗎?

df <- df %>% group_by(levelled) %>% filter(any(direction == "down"))

您可以使用 -

subset(df, levelled %in% levelled[direction == 'down'])

#   condition levelled direction
#9         c1        c        up
#10        c2        c        up
#11        c3        c      down
#12        c4        c        up

dplyr您可以將其寫為 -

library(dplyr)

df %>% filter(levelled %in% levelled[direction == 'down'])

暫無
暫無

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

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