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

Get first instance of condition in longitudinal dataset otherwise last instance

ll <- data.table(ID=rep(1:3,each=3),
    num=c(1:9),
    var=c("a","b","c","a","b","b","a","c","c"))
setorder(ll,ID,num,var)

Now I´d like to retrieve the first instance of "c" if present, but if not present I´s like to retrieve the last instance of not "c".

  ll[,.SD[var=="c"][1],by=.(ID)]

gives me the first instance of "c", but how can I also get the last instance of not "c"?

Desired result:

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   num    var
   <int> <int> <char>
1:     1     3      c
2:     2     6      b
3:     3     8      c

>Solution :

One way could be:

ll[, .SD[if (any(var == 'c')) var == 'c' & rowid(var) == 1L else .N], by = .(ID)]

Output:

   ID num var
1:  1   3   c
2:  2   6   b
3:  3   8   c
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