Question
Why Rcpp my Rcpp function inside the data.table produce a different (& wrong) result compared to using outside the join?
Example
I have two data.table s, and I want to find the Euclidean distance between each pair of coordinates in both tables.
To calculate the distance, I defined two functions: one in the R base and the other in Rcpp .
library(Rcpp) library(data.table) rEucDist <- function(x1, y1, x2, y2) return(sqrt((x2 - x1)^2 + (y2 - y1)^2)) cppFunction('NumericVector cppEucDistance(NumericVector x1, NumericVector y1, NumericVector x2, NumericVector y2){ int n = x1.size(); NumericVector distance(n); for(int i = 0; i < n; i++){ distance[i] = sqrt(pow((x2[i] - x1[i]), 2) + pow((y2[i] - y1[i]), 2)); } return distance; }') dt1 <- data.table(id = rep(1, 6), seq1 = 1:6, x = c(1:6), y = c(1:6)) dt2 <- data.table(id = rep(1, 6), seq2 = 7:12, x = c(6:1), y = c(6:1))
At the first connection, then calculating the distance, both functions produce the same result
dt_cpp <- dt1[ dt2, on = "id", allow.cartesian = T] dt_cpp[, dist := cppEucDistance(x, y, ix, iy)] dt_r <- dt1[ dt2, on = "id", allow.cartesian = T] dt_r[, dist := rEucDist(x, y, ix, iy)] all.equal(dt_cpp$dist, dt_r$dist)
However, if I make a calculation in a compound, the results are different; The cpp version is incorrect.
dt_cppJoin <- dt1[ dt2, { (cppEucDistance(x, y, ix, iy)) }, on = "id", by = .EACHI ] dt_rJoin <- dt1[ dt2, { (rEucDist(x, y, ix, iy)) }, on = "id", by = .EACHI ] all.equal(dt_cppJoin$V1, dt_rJoin$V1)
What happens with an Rcpp implementation that forces the connection version to give a different result?