简体   繁体   中英

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. (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. However I want to be able to find it's R-squared value with respect to y=x? Does anyone know how I can go about doing this?

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. Thank you!

If you want the R-squared of the regression from y on x you should calculate a linear model. You can do this with model<-lm(y~x) . WIth summary(model) you can find all useful details, even the R-squared.

Here's one approach with lm from base R.

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. You can use 0 + to fix the intercept and offset() to fix the x term. Unfortunately, summary() doesn't seem to work correctly, but we can calculate r.squared ourselves.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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