R数据表:将行值与组值进行比较 [英] R data table: compare row value to group values

查看:128
本文介绍了R数据表:将行值与组值进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将每行的值与该组的值进行比较。



例如,我从:

  x = data.table(id = c(1,1,1,2,2,2),price = c(100,110,120,100,100,120))
> x
id价格
1:1 100
2:1 110
3:1 120
4:2 100
5:2 100
6:2 120

,并希望到达:

 >点¯x
编号价nb_cheaper_prices_per_id
1分配:1 100 0
2:1 110 1
3分配:1 120 2
4分配:2 100 0
5分配: 2 100 0
6:2 120 2

我尝试:

  X [,SUM(价格< .SD [,价格]),通过= ID] 

但是,这并不正常工作。


解决方案

  X [,更便宜:=地板(排名(价格)) -  1,= ID] 
#标识的价格便宜
#1:1 100 0
#2 :1 110 1
#3:1 120 2
#4:2 100 0
#5:2 100 0
#6:2 120 2

?rank 将对每个组中的值进行排名。我添加了?floor 以取消关系处理的效果。第二个选项是使用 ties.method =min。最后,从等级中减去 1 ,从0开始。


I would like to compare the value of each row to the values of the group.

For example, I start with:

x = data.table( id=c(1,1,1,2,2,2), price=c(100,110,120,100,100,120) )
> x
   id price
1:  1   100
2:  1   110
3:  1   120
4:  2   100
5:  2   100
6:  2   120

and would like to arrive to:

> x
   id price nb_cheaper_prices_per_id
1:  1   100                        0
2:  1   110                        1
3:  1   120                        2
4:  2   100                        0
5:  2   100                        0
6:  2   120                        2

I tried:

x[, sum(price<.SD[,price]), by=id]

but that does not work.

解决方案

x[,cheaper := floor(rank(price))-1, by=id]
#    id price cheaper
# 1:  1   100       0
# 2:  1   110       1
# 3:  1   120       2
# 4:  2   100       0
# 5:  2   100       0
# 6:  2   120       2

?rank will rank the values in each group. I added ?floor to cancel the effects of the handling of ties. A second option is to use ties.method="min". Lastly, 1 is subtracted from the ranks to start at 0.

这篇关于R数据表:将行值与组值进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆