Home > database >  Creating a new column based on conditions by groups in R
Creating a new column based on conditions by groups in R

Time:11-20

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

CodePudding user response:

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

CodePudding user response:

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
  •  Tags:  
  • r
  • Related