[英]Creating a new column based on conditions by groups in R
I have a dataframe:我有一个 dataframe:
ID <- c(1,1,2,2,2,2,3,3,3,3,3,4,4,4)
Eval <- c(TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE)
df <- data.frame(ID,Eval)
As long as there is one FALSE in Eval
per ID
, there should be a column, say x, indicating TRUE
.只要每个
ID
的Eval
中有一个 FALSE,就应该有一列,比如 x,表示TRUE
。 How do I create this column?如何创建此列?
The output should be: output 应该是:
ID x
1 FALSE
2 TRUE
3 TRUE
4 FALSE
Use any
on the negated ( !
) 'Eval' after grouping by 'ID'在按“ID”分组后,在否定(
!
)“Eval”上使用any
library(dplyr)
df %>%
group_by(ID) %>%
summarise(x = any(!Eval))
-output -输出
# A tibble: 4 × 2
ID x
<dbl> <lgl>
1 1 FALSE
2 2 TRUE
3 3 TRUE
4 4 FALSE
As an alternative we could use %in%
with ifelse
:作为替代方案,我们可以将
%in%
与ifelse
一起使用:
library(dplyr)
df %>%
group_by(ID) %>%
summarise(x = ifelse(FALSE %in% Eval, TRUE, FALSE))
ID x
<dbl> <lgl>
1 1 FALSE
2 2 TRUE
3 3 TRUE
4 4 FALSE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.