在 data.table 中将 tail 与 by 结合 [英] combining tail with by in data.table
本文介绍了在 data.table 中将 tail 与 by 结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
按因子获取 data.table 尾行的最佳方法是什么?
What's the best way to get the tail row of a data.table by a factor?
说我有:
> dt <- data.table(category = c("A", "A", "B", "B", "B"), value = c(1,2,3,4,5))
> dt
category value
1: A 1
2: A 2
3: B 3
4: B 4
5: B 5
我想得到这个,但我不确定最有效的方法:
I want to get this, but I'm not sure the most efficient way to do it:
category value
1: A 2
2: B 5
推荐答案
我们可以使用last
dt[,list(value=last(value)) , by = category]
# category value
#1: A 2
#2: B 5
如果有很多列
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
或者正如@Frank 提到的那样
Or as @Frank mentioned
unique(dt, by="category", fromLast=TRUE)
或者我们可以直接在 .SD
上使用 last
(正如评论中提到的@jangorecki)
Or we can use last
directly on .SD
(as @jangorecki mentioned in the comments)
dt[, last(.SD), category]
dplyr
中还有另一个 last
函数.所以,如果两个包都加载了,最好指定 data.table::last
以免被屏蔽.
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.
这篇关于在 data.table 中将 tail 与 by 结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文