Skip to content

Instantly share code, notes, and snippets.

@dantonnoriega
Last active August 15, 2019 20:51
Show Gist options
  • Save dantonnoriega/975c1f1f0a7b653bbe1bce514cb2b29f to your computer and use it in GitHub Desktop.
Save dantonnoriega/975c1f1f0a7b653bbe1bce514cb2b29f to your computer and use it in GitHub Desktop.
# a running list of really useful data.table tricks
# TOP 1,2 ... last row by some group id
## source: https://stackoverflow.com/questions/16325641/is-it-possible-to-extract-the-first-2-rows-for-each-date#comment23381259_16325932
## comment by @eddi
id <- c('date', 'userid')
dt[dt[, .I[1:2], by = id]$V1] # first 2 rows by id
dt[dt[, .I[.N], by = id]$V1] # last row by id (.N = length of group, .I = row index)
@rsangole
Copy link

Slightly easier syntax?

dt[, tail(.SD,1), by=.(col1, col2)]

@dantonnoriega
Copy link
Author

hmm not sure. id have to test. could be though!

@rsangole
Copy link

Yep.. it works!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment