1

I have a data set that looks like this:

data 
ID               Application                 Admission
1                FALSE                       FALSE
2                FALSE                       FALSE
2                TRUE                        FALSE
3                FALSE                       FALSE
3                TRUE                        FALSE
3                TRUE                        TRUE

I want to somehow group the rows by ID and then remove everything but the last row for that ID. It would look like this:

ID               Application                 Admission
1                FALSE                       FALSE
2                TRUE                        FALSE
3                TRUE                        TRUE

I'm fairly new to coding so I just went one by one and removed rows individually. Is there a better way to do this? Thank you.

  • [Already answered, you can visit](https://stackoverflow.com/questions/1313120/retrieving-the-last-record-in-each-group-mysql) – Amy Sep 21 '18 at 14:57
  • @Amy That answer is in MySQL, CarolynGrace is asking for an R solution – divibisan Sep 21 '18 at 15:01
  • If you use the data.table package and convert it to a data.table, there's `unique(data, by="ID", fromLast = TRUE)` (seeing if I can find a dupe...) – Frank Sep 21 '18 at 15:55
  • @divi & Rich - There are answers to this question (like Wen's) that don't apply to the first & last one you linked, so not a great dupe. Neither is the one I added, though (which is specifically about data.table)... – Frank Sep 21 '18 at 16:02
  • A slight variation of a data.table answer - `setDT(data)` `setkey(data,ID)` `data[J(unique(ID)),mult="last"]` – Debbie Sep 21 '18 at 16:09

2 Answers2

2

From base R

df[!duplicated(df$ID,fromLast = T),]
  ID Application Admission
1  1       FALSE     FALSE
3  2        TRUE     FALSE
6  3        TRUE      TRUE
BENY
  • 317,841
  • 20
  • 164
  • 234
0

Try:

library(dplyr)
df %>% group_by(ID) %>% slice(n())
# A tibble: 3 x 3
# Groups:   ID [3]
     ID Application Admission
  <int>       <lgl>     <lgl>
1     1       FALSE     FALSE
2     2        TRUE     FALSE
3     3        TRUE      TRUE
nghauran
  • 6,648
  • 2
  • 20
  • 29