按行优化数据 table

Optimize rowwise over a data table

我有一个数据 table 看起来像这样:

library(data.table)
set.seed(1)

# Number of rows in the data table
obs <- 10^2

# Generate representative data
DT <- data.table(
  V1 = sample(x =  1:10, size = obs, replace = TRUE),
  V2 = sample(x = 11:20, size = obs, replace = TRUE),
  V3 = sample(x = 21:30, size = obs, replace = TRUE)
)

和一个向量化函数fn_calibrate,它根据输入变量opt计算输出变量V4

fn_calibrate <- function(opt) {

  # Calculate some new value V4 that's dependent on opt
  DT[, V4 := V1 * sqrt(V2) / opt ]

  # Calculate the residual sum of squares (RSS) between V4 and a target value V3
  DT[, rss := abs(V3 - V4)^2]

  # Return the RSS
  return(DT[, rss])

}

现在,我想使用 optimize 函数执行按行优化,即 找到 opt 的值,使每行的 RSS 最小化.

我希望通过 data.table by = 语法来实现,例如:

# Run the optimizer rowwise
DT[, opt := optimize(f = fn_calibrate, interval = c(0.1, 1), tol = .0015)$minimum, by = seq_len(nrow(DT))]

代码 return 错误 invalid function value in 'optimize' 因为 fn_calibrate 函数当前被写入 (DT[, ...]) return [=] 的整个向量23=] 的长度 nrow(DT),而不是一次仅一行的标量。

我的问题是:有没有办法让优化器也有 fn_calibrate return 行结果?

编辑

我意识到在数据框的上下文中提出并回答了一个相关问题 ,尽管接受的答案使用 for 循环,而 我宁愿使用高效的数据 table by 语法,如果可能的话 。上面的 RepRex 很简单(100 行),但我的实际数据 table 更大(250K 行)。

fcn_calibrate不需要矢量化,使用data.table语法。

您可以将 V1,V2,V3,opt 作为参数传递,而 optimize 仅在 opt 上传递:

fn_calibrate <- function(V1,V2,V3,opt) {
  
  # Calculate some new value V4 that's dependent on opt
  V4 = V1 * sqrt(V2) / opt
  
  # Calculate the residual sum of squares (RSS) between V4 and a target value V3
  rss = abs(V3 - V4)^2
  
  # Return the RSS
  return(rss)
  
}

DT[, opt := optimize(f = function(opt) fn_calibrate(V1,V2,V3,opt),
                     interval = c(0.1, 1), tol = .0015)$minimum,
                     by = seq_len(nrow(DT))]

      V1    V2    V3       opt
     <int> <int> <int>     <num>
  1:     9    13    21 0.9990479
  2:     4    20    30 0.5962869
  3:     7    13    24 0.9992591
  4:     1    11    29 0.1142778
  5:     2    16    29 0.2756422
  6:     7    16    29 0.9656941
  7:     2    14    29 0.2578275
  8:     3    19    26 0.5028686
  9:     1    15    26 0.1490109
...