【发布时间】:2022-06-10 18:48:10
【问题描述】:
我想在dplyr 管道中编写case_when 代码。但是,我正在尝试在其中添加多个案例。
例如:如果一个有如下数据框
| id | purchases |
|---|---|
| a | need |
| a | want |
| a | none |
| b | want |
| b | need |
| c | need |
| c | need |
| c | want |
| d | none |
| d | none |
我想总结输出,以便需要每个 id 的前 2 个观察值的情况以及不考虑观察值“无”的情况,然后将 yes 放入新列中。如果不需要或不需要给定的 id,则 none,否则 no
输出应该如下:
| id | output |
|---|---|
| a | no |
| b | no |
| c | yes |
| d | none |
我的代码
actions %>% group_by (id) %>% arrange(id)
%>% summarise(output = case_when(first(purchases) == "need" & nth(purchases,2) =="need"~ "yes", "no"
我知道代码有点乱,因为我不知道当案例会导致yes 或no 时忽略none 观察的第二个条件是谁加起来
【问题讨论】: