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

R: Compare a row to all the rows that come before it

I have a dataframe that looks something like the following. For each row within a group, I would like to compare the ID to the ID of all rows before it. In a new column, the value would be "TRUE" if the ID of the row is the same to the ID of any row that comes before it, and "FALSE" if it is not the same to any row before it.

group    id      order
1 g1    27391    1   
2 g1    29381    2   
3 g2    27391    3   
4 g2    48401    1   
5 g2    27391    2   
6 g2    27391    3   
7 g2    48401    4   
8 g3    27391    1  
8 g3    48401    2  

So the output would look something like:

group    id      order  same?
1 g1    27391    1      NA
2 g1    29381    2      FALSE
3 g2    27391    3      TRUE
4 g2    48401    1      NA
5 g2    27391    2      FALSE
6 g2    27391    3      TRUE
7 g2    48401    4      TRUE
8 g3    27391    1      NA
8 g3    48401    2      FALSE

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

>Solution :

We may group by ‘group’, use duplicated on the ‘id’, replace the first element with NA and ungroup

library(dplyr)
dat %>%
   group_by(group) %>% 
   mutate(same = replace(duplicated(id), 1, NA)) %>%
   ungroup
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