如何将复杂的方程放入R公式中? [英] How to put a complicated equation into a R formula?

查看:18
本文介绍了如何将复杂的方程放入R公式中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们将树木的直径作为预测变量,将树木高度作为因变量.此类数据存在许多不同的方程,我们尝试对其中一些方程进行建模并比较结果.

We have the diameter of trees as the predictor and tree height as the dependent variable. A number of different equations exist for this kind of data and we try to model some of them and compare the results.

但是,我们无法弄清楚如何将一个方程正确地放入相应的R formula 格式.

However, we we can't figure out how to correctly put one equation into the corresponding R formula format.

可以以R中的trees数据集为例.

The trees data set in R can be used as an example.

data(trees)
df <- trees
df$h <- df$Height * 0.3048   #transform to metric system
df$dbh <- (trees$Girth * 0.3048) / pi   #transform tree girth to diameter

首先,一个似乎运行良好的等式示例:

First, the example of an equation that seems to work well:

form1 <- h ~ I(dbh ^ -1) + I( dbh ^ 2)  
m1 <- lm(form1, data = df)
m1

Call:
lm(formula = form1, data = df)

Coefficients:
(Intercept)    I(dbh^-1)     I(dbh^2)  
27.1147      -5.0553       0.1124  

系数abc是估计出来的,这是我们感兴趣的.

Coefficients a, b and c are estimated, which is what we are interested in.

现在有问题的等式:

尝试像这样适合它:

form2 <- h ~ I(dbh ^ 2) / dbh + I(dbh ^ 2) + 1.3

给出错误:

m1 <- lm(form2, data = df)
Error in terms.formula(formula, data = data) 
invalid model formula in ExtractVars

我猜这是因为 / 被解释为嵌套模型而不是算术运算符?

I guess this is because / is interpreted as a nested model and not an arithmetic operator?

这不会出错:

form2 <- h ~ I(I(dbh ^ 2) / dbh + I(dbh ^ 2) + 1.3)
m1 <- lm(form2, data = df)

但结果不是我们想要的:

But the result is not the one we want:

m1
Call:
lm(formula = form2, data = df)

Coefficients:
(Intercept)  I(I(dbh^2)/dbh + I(dbh^2) + 1.3)  
19.3883                            0.8727  

外层I()中的整个项只给出一个系数,这似乎是合乎逻辑的.

Only one coefficient is given for the whole term within the outer I(), which seems to be logic.

我们如何将第二个方程拟合到我们的数据中?

How can we fit the second equation to our data?

推荐答案

假设你使用的是 nls R 公式可以使用普通的 R 函数,H(a, b, c,D),所以公式可以是 h ~ H(a, b, c, dbh) 并且这有效:

Assuming you are using nls the R formula can use an ordinary R function, H(a, b, c, D), so the formula can be just h ~ H(a, b, c, dbh) and this works:

# use lm to get startingf values
lm1 <- lm(1/(h - 1.3) ~ I(1/dbh) + I(1/dbh^2), df)
start <- rev(setNames(coef(lm1), c("c", "b", "a")))

# run nls
H <- function(a, b, c, D) 1.3 + D^2 / (a + b * D + c * D^2)
nls1 <- nls(h ~ H(a, b, c, dbh), df, start = start)

nls1 # display result

绘制输出:

plot(h ~ dbh, df)
lines(fitted(nls1) ~ dbh, df)

这篇关于如何将复杂的方程放入R公式中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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