简体   繁体   中英

Creating a new column based on conditions by groups in R

I have a 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 . How do I create this column?

The output should be:

ID  x 
 1  FALSE 
 2  TRUE 
 3  TRUE
 4  FALSE

Use any on the negated ( ! ) 'Eval' after grouping by 'ID'

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM