r - 使用 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" ~ #??
)
)
解决方案
你想要那样的东西吗?
df <- df %>% group_by(levelled) %>% filter(any(direction == "down"))
推荐阅读
- indexing - 尝试索引 sphinx.conf 时出现 Sphinx 3 2.1 错误
- typescript - TypeScript:跨多种类型的接口?
- android - 如何使用Navigation框架实现分层导航?
- scala - Spark Job 没有向 Kafka 主题发布消息
- html - jQuery Ajax:html按钮在单击时保持静止而不调用ajax函数
- scala - 使用结构化 Spark 流从 Kafka 主题读取 AVRO 消息时出现问题(Spark 版本 2.3.1.3.0.1.0-187/Scala 版本 2.11.8)
- webpack - Rails 6、webpack 和tippy.js 给出“tippy 未定义”——我在哪里调用tippy() 函数?
- angular - PrimeNg 删除严重性图标
- windows - CreateFileA 访问windows文件系统驱动返回INVALID_HANDLE_VALUE
- android - Android RoomDB 动态选择参数