We can use last
dt[,list(value=last(value)) , by = category]
# category value
#1: A 2
#2: B 5
If there are many columns
dt[, lapply(.SD, last), category]
Or another option if the data is ordered by 'category'
dt[!duplicated(category, fromLast=TRUE)]
# category value
#1: A 2
#2: B 5
Or as @Frank mentioned
unique(dt, by="category", fromLast=TRUE)
Or we can use last
directly on .SD
(as @jangorecki mentioned in the comments)
dt[, last(.SD), category]
There is another last
function from dplyr
. So, if both the packages are loaded, it is best to specify the data.table::last
so that it won't get masked.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…