英文:
Determine if value in one column comes before value in another column in R
问题
我想要创建一个新列EDbeforesurgery
,如果在一个组内基于变量order
,ED
=1的情况出现在surgery
=1之前。
这是我的数据框的一部分示例:
df <- data.frame(
group = c(1, 1, 1, 2, 2, 3, 3),
order = c(1, 2, 3, 1, 2, 1, 2),
ED = c(1, 0, 0, 1, 1, 0, 0),
surgery = c(0, 0, 1, 0, 0, 0, 1))
所以对于group
1, 2, 3,理想的输出分别是Y
, N
, N
。
英文:
I would like to create a new column EDbeforesurgery
if instances where ED
=1 comes before surgery
=1 within a group based on the variable order
.
Here is a snippet of my dataframe:
df <- data.frame(
group = c(1, 1, 1, 2, 2, 3, 3),
order = c(1, 2, 3, 1, 2, 1, 2),
ED = c(1, 0, 0, 1, 1, 0, 0),
surgery = c(0, 0, 1, 0, 0, 0, 1))
So the ideal output for group
1, 2, 3 would be Y
, N
, N
, respectively.
答案1
得分: 3
你可以尝试:
library(dplyr)
df %>%
mutate(手术前ED = any(cummax(急诊科) > cummax(手术)) && any(手术 == 1L), .by = 组)
组 顺序 急诊科 手术 手术前ED
1 1 1 1 0 TRUE
2 1 2 0 0 TRUE
3 1 3 0 1 TRUE
4 2 1 1 0 FALSE
5 2 2 1 0 FALSE
6 3 1 0 0 FALSE
7 3 2 0 1 FALSE
英文:
You can try:
library(dplyr)
df %>%
mutate(EDbeforesurgery = any(cummax(ED) > cummax(surgery)) && any(surgery == 1L), .by = group)
group order ED surgery EDbeforesurgery
1 1 1 1 0 TRUE
2 1 2 0 0 TRUE
3 1 3 0 1 TRUE
4 2 1 1 0 FALSE
5 2 2 1 0 FALSE
6 3 1 0 0 FALSE
7 3 2 0 1 FALSE
答案2
得分: 2
你可以尝试使用 `dplyr` 中的这个选项:
```r
library(dplyr)
df %>%
group_by(group) %>%
mutate(EDbeforesurgery = isTRUE(first(order[ED == 1]) < first(order[surgery == 1]))) %>%
ungroup()
# group order ED surgery EDbeforesurgery
# 1 1 1 1 0 TRUE
# 2 1 2 0 0 TRUE
# 3 1 3 0 1 TRUE
# 4 2 1 1 0 FALSE
# 5 2 2 1 0 FALSE
# 6 3 1 0 0 FALSE
# 7 3 2 0 1 FALSE
英文:
You can try this dplyr
option:
library(dplyr)
df %>%
group_by(group) %>%
mutate(EDbeforesurgery = isTRUE(first(order[ED == 1]) < first(order[surgery == 1]))) %>%
ungroup()
# group order ED surgery EDbeforesurgery
# 1 1 1 1 0 TRUE
# 2 1 2 0 0 TRUE
# 3 1 3 0 1 TRUE
# 4 2 1 1 0 FALSE
# 5 2 2 1 0 FALSE
# 6 3 1 0 0 FALSE
# 7 3 2 0 1 FALSE
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论