简体   繁体   English

在 R 中用我自己的回归 model 计算 R 平方

[英]Calculating R-squared with my own regression model in R

I'm working on a project in R, and have run into an issue.I used the Trendline function from the basicTrendline funcion, and it did all the work for me.我正在 R 中开展一个项目,但遇到了问题。我使用了基本趋势线功能中的趋势线 function,它为我完成了所有工作。 (YAY). (耶)。

However, my hypothesis is the data would follow a trendline of y=x, but the basicTrendline function gave me y=0.96583x + 0.0029502, which is very close.但是,我的假设是数据将遵循 y=x 的趋势线,但基本趋势线 function 给了我 y=0.96583x + 0.0029502,非常接近。 However I want to be able to find it's R-squared value with respect to y=x?但是我希望能够找到它相对于 y=x 的 R 平方值? Does anyone know how I can go about doing this?有谁知道我该怎么做 go

I'm fairly familiar with statistics, but not R, so I also don't know how to / if you can assign a function (like y=x) to a variable, but if you know how, I would also appreciate that.我对统计数据相当熟悉,但不是 R,所以我也不知道如何/是否可以将 function(如 y=x)分配给变量,但如果您知道如何,我也将不胜感激。 Thank you!谢谢!

If you want the R-squared of the regression from y on x you should calculate a linear model.如果你想要从 y 到 x 的回归的 R 平方,你应该计算一个线性 model。 You can do this with model<-lm(y~x) .您可以使用model<-lm(y~x)来做到这一点。 WIth summary(model) you can find all useful details, even the R-squared.使用summary(model) ,您可以找到所有有用的细节,甚至是 R 平方。

Here's one approach with lm from base R.这是从基础 R 使用lm的一种方法。

Generate some data.生成一些数据。

set.seed(1) 
data <- data.frame(x = 1:10, y = 1:10 + runif(-1,1,n=10))
plot(data)
abline(a=0, b=1)

在此处输入图像描述

Now fit the linear model.现在安装线性 model。 You can use 0 + to fix the intercept and offset() to fix the x term.您可以使用0 +来修复截距和offset()来修复x项。 Unfortunately, summary() doesn't seem to work correctly, but we can calculate r.squared ourselves.不幸的是, summary()似乎无法正常工作,但我们可以自己计算 r.squared。

Model <- lm(y~0 + offset(x),data)
Residuals <- summary(Model)$residuals
SumResSquared <- sum(Residuals^2)
TotalSumSquares <- sum((data$y - mean(data$y))^2)
RSquared <- 1 - (SumResSquared/TotalSumSquares)
RSquared
#[1] 0.9582742

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

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