【问题标题】:inner join with multiple conditions r data table多条件内连接r数据表
【发布时间】:2019-08-03 13:26:21
【问题描述】:

我正在尝试使用具有多个相当动态条件的数据表进行内部连接。我被语法绊倒了。首先,我创建了两个对象,xx2,我想用它们进行内部连接。

set.seed(1)
#generate data
x = data.table(CJ(t=1:10, d=1:3,p1s=seq(1,3,by=0.1),p1sLAST=seq(1,3,by=0.1)))
x[d==1,p1sLAST:=3]
x=x[p1s<=p1sLAST]
x2 = data.table(CJ(tprime=1:10, p1sLASTprm=seq(1,3,by=0.1)))

对象:

> x
    t d p1s p1sLAST
1:  1 1 1.0     3.0
2:  1 1 1.0     3.0
3:  1 1 1.0     3.0
4:  1 1 1.0     3.0
5:  1 1 1.0     3.0
---                 
9026: 10 3 2.8     2.9
9027: 10 3 2.8     3.0
9028: 10 3 2.9     2.9
9029: 10 3 2.9     3.0
9030: 10 3 3.0     3.0


> x2
    tprime p1sLASTprm
1:      1        1.0
2:      1        1.1
3:      1        1.2
4:      1        1.3
5:      1        1.4
---                  
206:     10        2.6
207:     10        2.7
208:     10        2.8
209:     10        2.9
210:     10        3.0

现在,我想在一个内部连接中完成最后三个步骤。

joined = x[,x2[],by=names(x)]
joined=joined[p1sLASTprm==p1s & d!=3 | d==3 & p1sLASTprm==3]
joined=joined[tprime==t+1]

导致最终输出:

> joined
       t  d  p1s   p1sLAST  tprime    p1sLASTprm
    1: 1 1    1.0     3.0      2        1.0
    2: 1 1    1.1     3.0      2        1.1
    3: 1 1    1.2     3.0      2        1.2
    4: 1 1    1.3     3.0      2        1.3
    5: 1 1    1.4     3.0      2        1.4
    ---                                  
    4343: 9 3 2.8     2.9     10        3.0
    4344: 9 3 2.8     3.0     10        3.0
    4345: 9 3 2.9     2.9     10        3.0
    4346: 9 3 2.9     3.0     10        3.0
    4347: 9 3 3.0     3.0     10        3.0

【问题讨论】:

    标签: r data.table inner-join cross-join


    【解决方案1】:

    我认为单个内部联接无法完成这 3 个步骤,因为存在 | 并且很可能需要合并结果。

    一种更节省内存的方法可能是:

    ux <- unique(x)[, upt := t+1]
    rbindlist(list(
        ux[d!=3][x2,
            c(mget(names(ux)), mget(names(x2))),
            on=c("p1s"="p1sLASTprm", "upt"="tprime"),
            nomatch=0L],
        ux[d==3][x2[p1sLASTprm==3],
            c(mget(names(ux)), mget(names(x2))),
            on=c("upt"="tprime"),
            nomatch=0L]
    ))
    

    【讨论】:

    • 如果我在数据表 x2 中有其他列,我如何确保它们被包含在内?把它们都打出来太多了,但我可以做类似的事情吗? q[d!=3][q2, c(.SD, .(p1sLASTprm=p1s,c2=c2,c3=c3)), on=c("p1s"="p1sLASTprm", "upt"="tprm"), nomatch=0L,allow.cartesian=TRUE] 而是……othercols = c('c1','c2') 然后q[d!=3][q2, c(.SD, .(p1sLASTprm=p1s,othercols)), on=c("p1s"="p1sLASTprm", "upt"="tprm"), nomatch=0L,allow.cartesian=TRUE]
    • 我添加了一些更通用的内容,但是当 uxx2 具有相同的列名(即输出可能包含具有相同名称的列)时,事情可能会变得有些奇怪。但这也可以解决:)。有关一般方法,请参阅此链接:
    猜你喜欢
    • 2019-03-14
    • 2016-11-12
    • 2021-04-01
    • 2018-04-02
    • 1970-01-01
    • 2023-03-04
    • 2015-09-19
    • 2015-10-09
    • 1970-01-01
    相关资源
    最近更新 更多