我有一个函数 Q(x|delta): R^n --> R 我想拟合非线性分位数回归。函数 Q(.) 使用了一些矩阵运算,不使用它会非常复杂。问题在于,当公式参数中使用的函数中存在矩阵运算时,nlrq(非线性分位数回归)和 nls(非线性回归)似乎不起作用。
为了说明,考虑更简单的函数 F(x1,x2|a,b,c),当我不使用矩阵运算时,我可以在 nlrq 和 nls 函数的公式参数中使用它,但在公式中不起作用用矩阵运算编写时的参数。
library('quantreg')
## Generating the data
x1<- rnorm(200)
x2<- rnorm(200)
y<- 1+3*sin(x1)+2*cos(x2) +rnorm(200)
Dat<- data.frame(y,x1,x2)
## The function F1 without matrix operation
F1<- function(x_1, x_2, a, b,c){a+b*sin(x_1)+c*cos(x_2)}
## The function F2 with matrix operation
F2<- function(x_1, x_2, a, b,c){t(c(1,sin(x_1),cos(x_2)))%*%c(a,b,c)}
## Both functions work perfectly
F1(x_1=3, x_2=2, a=1, b=3,c=2)
F2(x_1=3, x_2=2, a=1, b=3,c=2)
## But only F1 can be estimated by nls and nlrq
nls_1<-nls(y ~ F1(x_1 = x1, x_2 = x2, a = 1, b, c),
data = Dat, start = list(b = 3, c = 2))
nlrq_1<-nlrq(y ~ F1(x_1 = x1, x_2 = x2, a = 1, b, c),
data = Dat, start = list(b = 3, c = 2), tau = 0.9)
## When F2 is used in the formula argument an error happens
nls_2<-nls(y ~ F2(x_1 = x1, x_2 = x2, a = 1, b, c),
data = Dat, start = list(b = 3, c = 2))
nlrq_2<-nlrq(y ~ F2(x_1 = x1, x_2 = x2, a = 1, b, c),
data = Dat, start = list(b = 3, c = 2), tau = 0.9)
错误是
Error in t(c(1, sin(x_1), cos(x_2))) %*% c(a, b, c) : non-conformable arguments
.我相信如果有人设法通过 nls 和 nlrq 使用矩阵运算来估计 F2,我将能够在我的其他函数中使用相同的解决方案。Dat 的大小为 200x3。
非常感谢。
最佳答案
您的函数 F2()
不适用于向量参数 x_1
, x_2
, ... 因为 c(...)
只构建一个长向量(不是矩阵)。
看:
F1(x_1=c(3,5), x_2=c(2,4), a=1, b=3,c=2)
F2(x_1=c(3,5), x_2=c(2,4), a=1, b=3,c=2)
结果:
#> F1(x_1=c(3,5), x_2=c(2,4), a=1, b=3,c=2)
#[1] 0.5910664 -3.1840601
#> F2(x_1=c(3,5), x_2=c(2,4), a=1, b=3,c=2)
#error in t(c(1, sin(x_1), cos(x_2))) %*% c(a, b, c) : ...
函数
nls()
和 nlrq()
正在将向量(即数据帧中的列 Dat
)发送到您的函数 F2()
(分别为 F1()
)。以下是
F2()
的一些矢量化定义:# other definitions for F2()
F2 <- function(x_1, x_2, a, b,c) cbind(1,sin(x_1),cos(x_2)) %*% c(a,b,c)
F2(x_1=c(3,5), x_2=c(2,4), a=1, b=3,c=2)
F2 <- function(x_1, x_2, a, b,c) t(rbind(1,sin(x_1),cos(x_2))) %*% c(a,b,c)
F2(x_1=c(3,5), x_2=c(2,4), a=1, b=3,c=2)
F2 <- function(x_1, x_2, a, b,c) colSums(rbind(1,sin(x_1),cos(x_2)) * c(a,b,c))
F2(x_1=c(3,5), x_2=c(2,4), a=1, b=3,c=2)
F2 <- function(x_1, x_2, a, b,c) crossprod(rbind(1,sin(x_1),cos(x_2)), c(a,b,c))
F2(x_1=c(3,5), x_2=c(2,4), a=1, b=3,c=2)
F2 <- function(x_1, x_2, a, b,c) tcrossprod(c(a,b,c), cbind(1,sin(x_1),cos(x_2)))
F2(x_1=c(3,5), x_2=c(2,4), a=1, b=3,c=2)
关于r - "Error in ... %*% ... : non-conformable arguments"在回归中使用自己的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42813618/