【发布时间】:2016-08-31 04:03:58
【问题描述】:
假设我们有以下data.table:
library(data.table)
dt <- data.table(x=c(-0.01, -0.001, 0, 0.01,0.02,0.03,1,3,4,10,20,25), value=c(rep(1,3), rep(2, 3), rep(3, 2), rep(4, 2), rep(5, 2)))
然后,我使用以下内容指定间隔:
library(Hmisc)
dt[, int:=cut2(x, cuts=c(-Inf, 0.01, 1, 4, 20, Inf))]
返回,
x value int
1: -0.010 1 [ -Inf, 0.01)
2: -0.001 1 [ -Inf, 0.01)
3: 0.000 1 [ -Inf, 0.01)
4: 0.010 2 [ 0.01, 1.00)
5: 0.020 2 [ 0.01, 1.00)
6: 0.030 2 [ 0.01, 1.00)
7: 1.000 3 [ 1.00, 4.00)
8: 3.000 3 [ 1.00, 4.00)
9: 4.000 4 [ 4.00,20.00)
10: 10.000 4 [ 4.00,20.00)
11: 20.000 5 [20.00, Inf]
12: 25.000 5 [20.00, Inf]
假设有新的data.table
dtnew <- data.table(x=c(-0.001, 0.4, 0.3, 5, 25))
x
1: -0.001
2: 0.400
3: 0.300
4: 5.000
5: 25.000
我想要的是将值dtnew 与dt 中的间隔匹配,以便我可以在dt 中获得value。预期回报为
x value int
1: -0.001 1 [ -Inf, 0.01)
2: 0.400 2 [ 0.01, 1.00)
3: 0.300 2 [ 0.01, 1.00)
4: 5.000 4 [ 4.00,20.00)
5: 25.000 5 [20.00, Inf]
我已尝试将间隔分配给dtnew,以便我可以使用以下内容merge(dtnew, dt, by = 'int'):
dtnew[, int:=cut2(y, cuts=c(-Inf, 0.01, 1, 4, 20, Inf))] 与dt 中使用的间隔相同。但是,第一行的间隔与dt不同,如下:
1: -0.001 -Inf
2: 0.400 [ 0.01, 1.00)
3: 0.300 [ 0.01, 1.00)
4: 5.000 [ 4.00,20.00)
5: 25.000 [20.00, Inf]
你能给我一些建议吗?
【问题讨论】:
标签: r data.table intervals