Skip to content

Wrong values in j with complex values if "by" has more than 1 group. #3639

Closed

Description

@eliocamp

I understand that complex number support is not fully implemented (see this issue), but this is weird and, very serious, IMHO, because it can be a big source of silent errors.

library(data.table)
set.seed(42)
data <- setDT(expand.grid(x = 1:10,
                    a = c("a", "b"),
                    b = 1:2))
data[, z := rnorm(1:.N) + rnorm(1:.N)*1i]


data2 <- data[, .(x = x, z = z), by = .(a, b)]

Now both data.tables should have the same data, but…

rbind(data[a == "b" & b == 2 & x == 1],
      data2[a == "b" & b == 2 & x == 1], use.names = TRUE)
#>    x a b                    z
#> 1: 1 b 2 0.4554501-1.0431189i
#> 2: 1 b 2 0.6359504+0.2765507i

The problems are not evently distributed:

setnames(data2, "z", "z2")
merged <- data2[data, on = c("x", "a", "b")]

library(ggplot2)
#> Registered S3 methods overwritten by 'ggplot2':
#>   method         from 
#>   [.quosures     rlang
#>   c.quosures     rlang
#>   print.quosures rlang
ggplot(merged, aes(x, abs(z - z2))) +
    geom_line() +
    facet_grid(a ~ b)

And it doesn’t happen if “by” has only one group

data2 <- data[, .(x = x, z = z), by = .(interaction(a, b, sep = "."))]


data[a == "b" & b == 2 & x == 1]$z == data2[interaction == "b.2" & x == 1]$z
#> [1] TRUE

Created on 2019-06-10 by the reprex package (v0.2.1)

Activity

  1. changed the title [-]Wrong values in j with complex values if "by" has more than 1 variable.[/-] [+]Wrong values in j with complex values if "by" has more than 1 group.[/+] on Jun 10, 2019
  2. DavidArenburg commented on Jun 17, 2019

    @DavidArenburg
    Member

    Definitely looks like a bug. This doesn't happen with other classes.

  3. MichaelChirico commented on Jul 10, 2019

    @MichaelChirico
    Member

    TIL expand.grid creates an attribute:

    attr(data, 'out.attrs')
    $dim
     x  a  b 
    10  2  2 
    
    $dimnames
    $dimnames$x
     [1] "x= 1" "x= 2" "x= 3" "x= 4" "x= 5" "x= 6" "x= 7" "x= 8" "x= 9" "x=10"
    
    $dimnames$a
    [1] "a=a" "a=b"
    
    $dimnames$b
    [1] "b=1" "b=2"
    
  4. MichaelChirico commented on Jul 10, 2019

    @MichaelChirico
    Member

    A workaround is to store real and imaginary parts separately:

    `:=`(z_re = Re(z), z_im = Im(z))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions