1

我对 in 的评估迷失bydata.table将功能合并到一个功能中的正确方法是LJ什么LJ2

LJ <- function(dt_x_, dt_y_, by_)
{
    merge(
        dt_x_,
        dt_y_,
        by = eval(substitute(by_)), all.x = TRUE, sort = FALSE)
}
LJ2 <- function(dt_x_, dt_y_, by_)
{
    merge(
        dt_x_,
        dt_y_,
        by = deparse(substitute(by_)), all.x = TRUE, sort = FALSE)
}
LJ(
    data.table(A = c(1,2,3)),
    data.table(A = c(1,2,3), B = c(11,12,13)), 
    "A")
LJ2(
    data.table(A = c(1,2,3)),
    data.table(A = c(1,2,3), B = c(11,12,13)), 
    A)
4

1 回答 1

4

我认为这是一个坏主意。让用户始终传递一个字符值。你可以这样做:

LJ3 <- function(dt_x_, dt_y_, by_)
{ 
  by_ <- gsub('\"', "", deparse(substitute(by_)), fixed = TRUE)
  dt_y_[dt_x_, on = by_] 
}

LJ3(
  data.table(A = c(4,1,2,3)),
  data.table(A = c(1,2,3), B = c(11,12,13)), 
  A)
#   A  B
#1: 4 NA
#2: 1 11
#3: 2 12
#4: 3 13

LJ3(
  data.table(A = c(4,1,2,3)),
  data.table(A = c(1,2,3), B = c(11,12,13)), 
  "A")
#   A  B
#1: 4 NA
#2: 1 11
#3: 2 12
#4: 3 13

这个问题与 data.table 无关。in的by参数merge.data.table总是需要一个字符值,on.

编辑: @eddi 指出,如果您的列名中包含实际"的列名,上述操作将失败(通常您应该避免这种情况,但如果您fread的某些输入文件是由其他人准备的,则可能会发生这种情况)。

可以处理这种边缘情况的替代方法是:

LJ4 <- function(dt_x_, dt_y_, by_)
{ 
  by_ <- substitute(by_)
  if (!is.character(by_)) by_ <- deparse(by_)
  dt_y_[dt_x_, on = by_] 
}
于 2016-09-08T10:30:09.817 回答