data.table join and j-expression unexpected behavior

后端 未结 4 1608
无人及你
无人及你 2020-12-17 03:41

In R 2.15.0 and data.table 1.8.9:

d = data.table(a = 1:5, value = 2:6, key = \"a\")

d[J(3), value]
#   a value
#   3     4

d[J(3)         


        
4条回答
  •  天涯浪人
    2020-12-17 04:13

    As of data.table 1.9.3, the default behavior has been changed and the examples below produce the same result. To get the by-without-by result, one now has to specify an explicit by=.EACHI:

    d = data.table(a = 1:5, value = 2:6, key = "a")
    
    d[J(3), value]
    #[1] 4
    
    d[J(3), value, by = .EACHI]
    #   a value
    #1: 3     4
    

    And here's a slightly more complicated example, illustrating the difference:

    d = data.table(a = 1:2, b = 1:6, key = 'a')
    #   a b
    #1: 1 1
    #2: 1 3
    #3: 1 5
    #4: 2 2
    #5: 2 4
    #6: 2 6
    
    # normal join
    d[J(c(1,2)), sum(b)]
    #[1] 21
    
    # join with a by-without-by, or by-each-i
    d[J(c(1,2)), sum(b), by = .EACHI]
    #   a V1
    #1: 1  9
    #2: 2 12
    
    # and a more complicated example:
    d[J(c(1,2,1)), sum(b), by = .EACHI]
    #   a V1
    #1: 1  9
    #2: 2 12
    #3: 1  9
    

提交回复
热议问题