首页 > 解决方案 > 在 R 中向量化两个相似的函数适用于一个

问题描述

今天,我遇到了一个问题:两个几乎相同的函数在矢量化之前按预期工作,但在它之后,一个工作正常,另一个返回错误。

我正在研究各种估计器对残差和聚合函数的不同变换的稳健性。分位数回归和最小平方中位数是我正在做的特殊情况。

所以我写了下面的代码来看看最小二乘法是如何工作的,并发现如果模型参数作为不同的参数提供它可以正常工作,但如果它们以向量的形式出现则失败。例如,我需要第一个函数进行绘图(它可以方便地用于outer(...)获取值矩阵persp或仅提供f(x, y)persp3dfrom library(rgl),但第二个用于估计(R 优化器期望输入向量作为第一个参数)将进行最小化)。

MWE:

set.seed(105)
N <-  204
x <- rlnorm(N)
y <- 1 + x + rnorm(N)*sqrt(.1+.2*x+.3*x^2)
# A simple linear model with heteroskedastic errors

resfun <- function(x) return(x^2)
# Going to minimise a function of squared residuals...
distfun <- function(x) return(mean(quantile(x, c(0.25, 0.5, 0.5, 0.75)))) 
# ...which in this case is the trimean

penalty <- function(theta0, theta1) {
  r <- y - theta0 - theta1*x
  return(distfun(resfun(r)))
}

pen2 <- function(theta) {
  r <- y - theta[1] - theta[2]*x
  return(distfun(resfun(r)))
}

penalty(1, 1) # 0.5352602
pen2(c(1, 1)) # 0.5352602

vpenalty <- Vectorize(penalty)
vpen2 <- Vectorize(pen2)

vpenalty(1, 1) # 0.5352602
vpen2(c(1, 1))

Error in quantile.default(x, c(0.25, 0.5, 0.5, 0.75)) : 
missing values and NaN's not allowed if 'na.rm' is FALSE 

为什么即使在单个输入上也会vpen2被矢量化?pen2

标签: rfunctionvectorization

解决方案


正如jogo 所指出的,vpen2读取输入向量的元素并尝试取第一个。正确的方法是使用类似的东西

a <- matrix(..., ncol=2)
apply(a, 1, pen2)

这将从vpar2矩阵的每一行计算的值返回一个向量。


推荐阅读