首页 > 解决方案 > 使用 case_when() 和 filter() 根据 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数据框中,我提取了与direction == down列中具有相同级别的其他 3 行的行levelled。我想我应该尝试这样的事情,但我不知道在波浪号的右侧写什么:

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

标签: rtidyversesubset

解决方案


你想要那样的东西吗?

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

推荐阅读