简体   繁体   English

在R中得到图的二次方程项

[英]Get quadratic equation term of a graph in R

I need to find the quadratic equation term of a graph I have plotted in R. When I do this in excel, the term appears in a text box on the chart but I'm unsure how to move this to a cell for subsequent use (to apply to values requiring calibrating) or indeed how to ask for it in R. If it is summonable in R, is it saveable as an object to do future calculations with? 我需要找到我在R中绘制的图的二次方程项。当我在excel中执行此操作时,该术语出现在图表上的文本框中,但我不确定如何将其移动到单元格以供后续使用(应用于需要校准的值)或者实际上如何在R中请求它。如果它在R中可以调用,它是否可以作为一个对象来进行以后的计算?

This seems like it should be a straightforward request in R, but I can't find any similar questions. 这似乎应该是R中的直接请求,但我找不到任何类似的问题。 Many thanks in advance for any help anyone can provide on this. 非常感谢任何人可以提供的任何帮助。

All the answers provide aspects of what you appear at want to do, but non thus far brings it all together. 所有的答案都提供了你想要做的事情的方方面面,但到目前为止还没有将它们全部结合在一起。 Lets consider Tom Liptrot's answer example: 让我们来看看Tom Liptrot的答案示例:

fit <- lm(speed ~ dist + I(dist^2), cars)

This gives us a fitted linear model with a quadratic in the variable dist . 这给了我们一个拟合线性模型,其中变量dist具有二次方程。 We extract the model coefficients using the coef() extractor function: 我们使用coef()提取器函数提取模型系数:

> coef(fit)
 (Intercept)         dist    I(dist^2) 
 5.143960960  0.327454437 -0.001528367

So your fitted equation (subject to rounding because of printing is): 所以您的拟合方程(由于打印而变圆):

\\hat{speed} = 5.143960960 + (0.327454437 * dist) + (-0.001528367 * dist^2) \\ hat {speed} = 5.143960960 +(0.327454437 * dist)+( - 0.001528367 * dist ^ 2)

(where \\hat{speed} is the fitted values of the response, speed). (其中\\ hat {speed}是响应,速度的拟合值)。

If you want to apply this fitted equation to some data, then we can write our own function to do it: 如果你想将这个拟合方程应用于某些数据,那么我们可以编写自己的函数来做到这一点:

myfun <- function(newdist, model) {
    coefs <- coef(model)
    res <- coefs[1] + (coefs[2] * newdist) + (coefs[3] * newdist^2)
    return(res)
}

We can apply this function like this: 我们可以像这样应用这个函数:

> myfun(c(21,3,4,5,78,34,23,54), fit)
[1] 11.346494  6.112569  6.429325  6.743024 21.386822 14.510619 11.866907
[8] 18.369782

for some new values of distance ( dist ), Which is what you appear to want to do from the Q. However, in R we don't do things like this normally, because, why should the user have to know how to form fitted or predicted values from all the different types of model that can be fitted in R? 对于一些新的距离值( dist ),这是你似乎想从Q做的事情。然而,在R中我们通常不做这样的事情,因为,为什么用户必须知道如何形成拟合或者可以安装在R中的所有不同类型模型的预测值?

In R, we use standard methods and extractor functions. 在R中,我们使用标准方法和提取器函数。 In this case, if you want to apply the "equation", that Excel displays, to all your data to get the fitted values of this regression, in R we would use the fitted() function: 在这种情况下,如果要应用“等式”,Excel显示所有数据以获得此回归的拟合值,在R中我们将使用fitted()函数:

> fitted(fit)
        1         2         3         4         5         6         7         8 
 5.792756  8.265669  6.429325 11.608229  9.991970  8.265669 10.542950 12.624600 
        9        10        11        12        13        14        15        16 
14.510619 10.268988 13.114445  9.428763 11.081703 12.122528 13.114445 12.624600 
       17        18        19        20        21        22        23        24 
14.510619 14.510619 16.972840 12.624600 14.951557 19.289106 21.558767 11.081703 
       25        26        27        28        29        30        31        32 
12.624600 18.369782 14.057455 15.796751 14.057455 15.796751 17.695765 16.201008 
       33        34        35        36        37        38        39        40 
18.688450 21.202650 21.865976 14.951557 16.972840 20.343693 14.057455 17.340416 
       41        42        43        44        45        46        47        48 
18.038887 18.688450 19.840853 20.098387 18.369782 20.576773 22.333670 22.378377 
       49        50 
22.430008 21.93513

If you want to apply your model equation to some new data values not used to fit the model, then we need to get predictions from the model. 如果您想将模型方程应用于一些不适合模型的新数据值,那么我们需要从模型中获得预测。 This is done using the predict() function. 这是使用predict()函数完成的。 Using the distances I plugged into myfun above, this is how we'd do it in a more R-centric fashion: 利用我上面插入myfun的距离,我们就是以更加以R为中心的方式来实现的:

> newDists <- data.frame(dist = c(21,3,4,5,78,34,23,54))
> newDists
  dist
1   21
2    3
3    4
4    5
5   78
6   34
7   23
8   54
> predict(fit, newdata = newDists)
        1         2         3         4         5         6         7         8 
11.346494  6.112569  6.429325  6.743024 21.386822 14.510619 11.866907 18.369782

First up we create a new data frame with a component named "dist" , containing the new distances we want to get predictions for from our model. 首先,我们使用名为"dist"的组件创建一个新的数据框,其中包含我们希望从模型中获取预测的新距离。 It is important to note that we include in this data frame a variable that has the same name as the variable used when we created our fitted model. 值得注意的是,我们在此数据框中包含一个变量,该变量与我们创建拟合模型时使用的变量具有相同的名称。 This new data frame must contain all the variables used to fit the model, but in this case we only have one variable, dist . 这个新数据框必须包含用于拟合模型的所有变量,但在这种情况下,我们只有一个变量dist Note also that we don't need to include anything about dist ^2. 另请注意,我们不需要包含有关dist ^ 2的任何内容。 R will handle that for us. R将为我们处理。

Then we use the predict() function, giving it our fitted model and providing the new data frame just created as argument 'newdata' , giving us our new predicted values, which match the ones we did by hand earlier. 然后我们使用predict()函数,给它我们的拟合模型,并提供刚创建为参数'newdata'的新数据框,给我们新的预测值,这些值与我们之前手工制作的值相匹配。

Something I glossed over is that predict() and fitted() are really a whole group of functions. 我掩饰的东西是predict()fitted()实际上是一整套函数。 There are versions for lm() models, for glm() models etc. They are known as generic functions, with methods (versions if you like) for several different types of object. lm()模型的版本, glm()模型等。它们被称为泛型函数,有几种不同类型的对象的方法 (如果你喜欢的版本)。 You the user generally only need to remember to use fitted() or predict() etc whilst R takes care of using the correct method for the type of fitted model you provide it. 用户通常只需记住使用fitted()predict()等,而R负责使用您提供的拟合模型类型的正确方法。 Here are some of the methods available in base R for the fitted() generic function: 以下是base R中适用于fitted()泛型函数的一些可用方法:

> methods(fitted)
[1] fitted.default*       fitted.isoreg*        fitted.nls*          
[4] fitted.smooth.spline*

   Non-visible functions are asterisked

You will possibly get more than this depending on what other packages you have loaded. 根据您加载的其他软件包,您可能会得到更多。 The * just means you can't refer to those functions directly, you have to use fitted() and R works out which of those to use. *只是意味着你不能直接引用那些函数,你必须使用fitted()和R来确定使用哪些函数。 Note there isn't a method for lm() objects. 请注意,没有lm()对象的方法。 This type of object doesn't need a special method and thus the default method will get used and is suitable. 这种类型的对象不需要特殊的方法,因此default方法将被使用并且是合适的。

You can add a quadratic term in the forumla in lm to get the fit you are after. 你可以在lum的forumla中添加一个二次项,以获得你想要的拟合。 You need to use an I()around the term you want to square as in the example below: 你需要在你想要平方的术语周围使用I(),如下例所示:

plot(speed ~ dist, cars)

fit1 = lm(speed ~ dist, cars) #fits a linear model
abline(fit1) #puts line on plot
fit2 = lm(speed ~ I(dist^2) + dist, cars) #fits a model with a quadratic term
fit2line = predict(fit2, data.frame(dist = -10:130))
lines(-10:130 ,fit2line, col=2) #puts line on plot

To get the coefficients from this use: 要从这个用途中获得系数:

coef(fit2)

I dont think it is possible in Excel, as they only provide functions to get coefficients for a linear regression ( SLOPE , INTERCEPT , LINEST ) or for a exponential one ( GROWTH , LOGEST ), though you may have more luck by using Visual Basic. 我不认为它在Excel中是可能的,因为它们只提供函数来获得线性回归( SLOPEINTERCEPTLINEST )或指数( GROWTHLOGEST )的系数,尽管使用Visual Basic可能会有更多的运气。

As for R you can extract model coefficients using the coef function: 对于R,您可以使用coef函数提取模型系数:

mdl <- lm(y ~ poly(x,2,raw=T))
coef(mdl) # all coefficients
coef(mdl)[3] # only the 2nd order coefficient

I guess you mean that you plot X vs Y values in Excel or R, and in Excel use the "Add trendline" functionality. 我猜你的意思是你在Excel或R中绘制X和Y值,在Excel中使用“添加趋势线”功能。 In R, you can use the lm function to fit a linear function to your data, and this also gives you the "r squared" term (see examples in the linked page ). 在R中,您可以使用lm函数将线性函数拟合到数据中,这也为您提供了“r平方”项(请参阅链接页中的示例)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM