R-非线性回归(nls)和多项式相互作用(poly) [英] R - non linear regression (nls) and polynomial interactions (poly)

查看:111
本文介绍了R-非线性回归(nls)和多项式相互作用(poly)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我明确定义参数(在下面的示例中为"a"和"b"),则可以在R处运行nls回归.但是,如何在poly函数中用通用数量的变量/较高的递归编码nls?

I can run a nls regression at R if I explicitly define the parameters ("a" and "b" in the example below). However, how could I code the nls with a generic number of variables/higher degress in the poly function?

df <- data.frame(var1 = rnorm(100), var2 = rnorm(100))

p <- as.data.frame(poly(df$var2, degree = 2))

names(p) <- paste0("poly", names(p))

df <- cbind(df, p)

nls(var1 ~ a*poly1 + b*poly2, data = df, start = list(a = 1, b = 2))

无法像lm函数那样尝试代码:

Trying code, as is done with the lm function, is not possible:

nls(var1 ~ poly(var2, degree = 2), data = df, start = list(a = 1, b = 2)) #=> Error

推荐答案

您需要像在第一个示例中一样,将多项式项和您要估计的系数(ab)明确相乘.您可以通过矩阵乘法来做到这一点.

You need to explicitly multiply the polynomial terms and the coefficients you're estimating (a and b), as you did in the first example. You can do this with matrix multiplication.

请注意,poly返回一个矩阵,其中行与数据对齐,列为多项式项:

Note that poly returns a matrix, where the rows line up with your data and the columns are the polynomial terms:

> dim(poly(df$var2, degree = 2))
[1] 100   2

因此,与其将ab分开使用,不如将它们组合成一个向量,并将100 x 2矩阵与此2 x 1向量相乘:

Therefore, rather than working with a and b separately, combine them into a vector and multiply the 100 x 2 matrix with this 2 x 1 vector:

nls(var1 ~ poly(var2, degree = 2) %*% coef, data = df,
    start = list(coef = c(a = 1, b = 2)))

这给出了与您的工作示例相同的答案.

This gives the same answer as your working example.

这篇关于R-非线性回归(nls)和多项式相互作用(poly)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆