函数计算R中的R2(R平方)
问题描述:
我有一个观察和模拟数据的数据框,我想计算R2值。我希望有一个功能,我可以打电话给这个,但无法找到一个。我知道我可以写我自己的,并应用它,但我错过了一些明显的东西?我想要类似于
I have a dataframe with observed and modelled data, and I would like to calculate the R2 value. I expected there to be a function I could call for this, but can't locate one. I know I can write my own and apply it, but am I missing something obvious? I want something like
obs <- 1:5
mod <- c(0.8,2.4,2,3,4.8)
df <- data.frame(obs, mod)
R2 <- rsq(df)
# 0.85
答
您需要一点统计知识才能看到这一点。两个向量之间的R平方就是它们相关的平方。所以你可以定义你的函数为:
You need a little statistical knowledge to see this. R squared between two vectors is just the square of their correlation. So you can define you function as:
rsq <- function (x, y) cor(x, y) ^ 2