r - 在 R 中向量化两个相似的函数适用于一个
问题描述
今天,我遇到了一个问题:两个几乎相同的函数在矢量化之前按预期工作,但在它之后,一个工作正常,另一个返回错误。
我正在研究各种估计器对残差和聚合函数的不同变换的稳健性。分位数回归和最小平方中位数是我正在做的特殊情况。
所以我写了下面的代码来看看最小二乘法是如何工作的,并发现如果模型参数作为不同的参数提供它可以正常工作,但如果它们以向量的形式出现则失败。例如,我需要第一个函数进行绘图(它可以方便地用于outer(...)
获取值矩阵persp
或仅提供f(x, y)
给persp3d
from 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
解决方案
正如jogo 所指出的,vpen2
读取输入向量的元素并尝试取第一个。正确的方法是使用类似的东西
a <- matrix(..., ncol=2)
apply(a, 1, pen2)
这将从vpar2
矩阵的每一行计算的值返回一个向量。
推荐阅读
- reactjs - 在“materia-ui”中全局更新组件颜色/字体的最佳方法是什么?
- spring-boot - ELK:找不到一个或多个必需的 cgroup 文件或目录:/proc/self/cgroup
- javascript - 需要对 ExtendScript 中的对象进行 JSON 字符串化
- c++ - libc.so.6 部分 .tbss 中的 TLS 定义与非 TLS 定义不匹配
- nativescript - Nativescript 角度 radListView `itemSelecting` 示例
- python - Django 模板的日期过滤器导致表单值消失
- java - 将 AES 加密的输出转换为保留格式 (FPE)
- android - 底部导航 mShiftedMode 未找到
- github - 我的邮箱收到了。但是不知道怎么获取邮箱里的补丁,因为邮箱里的内容只有文字
- mysql - 在这种情况下我应该使用内连接吗?