查找data.table中的最大值

时间:2015-11-22 04:11:11

标签: r data.table

我有data.table

> x <- data.table(neighborhood = c("a", "b", "c"), cat1 = c(1, 1, 100), cat2 = c(50, 1, 1), cat3 = c(1, 1, 1))
> x
   neighborhood cat1 cat2 cat3
1:            a    1   50    1
2:            b    1    1    1
3:            c  100    1    1
> 

我想找到大值(例如)>= 50

我没有特定的方式我想看到这个(这是输出),但这可行:

> z
   neighborhood category value
1:            a     cat1    50
2:            c     cat2   100

我一直在捣乱我的大脑,但我想不出这个功能。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您可以使用melt()

melt(x, "neighborhood")[value >= 50, .SD, keyby = neighborhood]
#    neighborhood variable value
# 1:            a     cat2    50
# 2:            c     cat1   100

如果您不关心订单,可以使用

melt(x, "neighborhood")[value >= 50]
#    neighborhood variable value
# 1:            c     cat1   100
# 2:            a     cat2    50