Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ID  x 
 1  FALSE 
 2  TRUE 
 3  TRUE
 4  FALSE

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading