R/CJ.dt.R

Defines functions CJ.dt

Documented in CJ.dt

#' Cross join two data.tables
#'
#' The package data.table has a CJ() function which produces a data.table out of two vectors.
#' This function does the Cartesian product of two data.tables instead.
#'
#' @param X A data.table
#' @param Y A data.table
#' @return dt A data.table
#'
#' @keywords data.table CJ
#' @family helper
#' 
#' @examples
#' library(data.table)
#' a  <- data.table(a=1:2, b=letters[1:2])
#' b  <- data.table(c=3:4, d=letters[3:4])
#' ab <- CJ.dt(a,b)
#' 
#' @export
#' 

CJ.dt <- function(X, Y) {
    k <- NULL
    X <- X[, c(k = 1, .SD)]
    setkey(X, k)
    Y <- Y[, c(k = 1, .SD)]
    setkey(Y, NULL)
    X[Y, allow.cartesian = TRUE][, `:=`(k, NULL)]
} 

Try the optiRum package in your browser

Any scripts or data that you put into this service are public.

optiRum documentation built on May 5, 2022, 1:05 a.m.