R中使用case_when与filter基于单列值和另一列层级提取数据框子集
R数据框层级筛选实现方案
实现逻辑
你的需求可以拆解为两个简单步骤,不需要复杂的case_when逻辑:
- 提取所有
direction == "down"的行对应的levelled取值集合 - 筛选数据框中所有
levelled属于上述集合的行
正确代码
首先注意你原代码中的拼写错误:fiter需要修正为filter。
推荐最简写法:
library(dplyr) # 构造示例数据 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) # 筛选目标行 desired_output <- df %>% filter(levelled %in% levelled[direction == "down"])
运行后输出结果和你期望的完全一致:
condition levelled direction 9 c1 c up 10 c2 c up 11 c3 c down 12 c4 c up
如果你确实需要用case_when实现(非必要)
case_when是多条件分支判断函数,此处属于过度使用,但你可以按以下逻辑填写:
desired_output <- df %>% filter( case_when( # 只要当前行的levelled对应存在direction为down的记录就保留,返回TRUE,否则返回FALSE levelled %in% levelled[direction == "down"] ~ TRUE, TRUE ~ FALSE ) )
内容的提问来源于stack exchange,提问作者Wera
相关产品推荐
相关产品推荐

