我已经使用lm()对R中的数据集进行了多元回归分析,并且能够使用以下函数提取一年中每一天的系数。我还想提取一年中每一天的R2,但这似乎不能以相同的方式起作用。
与以下问题几乎相同: Print R-squared for all of the models fit with lmList 但是当我尝试这样做时,我得到“错误:$运算符对于原子向量无效”。如果可能,我还希望将其包含在同一函数中。如何以这种方式为每个doy提取R2?
#Create MR function for extracting coefficients
getCoef <- function(df) {
coefs <- lm(y ~ T + P + L + T * L + P * L, data = df)$coef
names(coefs) <- c("intercept", "T", "P", "L", "T_L", "P_L")
coefs
}
#Extract coefficients for each doy
coefs.MR_uM <- ddply(MR_uM, ~ doy, getCoef)```
答案 0 :(得分:2)
点是r.squared
存储在summary(lm(...))
中而不是lm(...)
中。这是提取R2
的函数的另一个版本:
library(plyr)
df <- iris
#Create MR function for extracting coefficients and R2
getCoef <- function(df) {
model <- lm(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width, data = df)
coefs <- model$coef
names(coefs) <- c("intercept", "Sepal.Width", "Petal.Length", "Petal.Width")
R2 <- summary(model)$r.squared
names(R2) <- c("R2")
c(coefs, R2)
}
#Extract coefficients and R2 for each Species
coefs.MR_uM <- ddply(df, ~ Species, getCoef)
coefs.MR_uM # output
Species intercept Sepal.Width Petal.Length Petal.Width R2
1 setosa 2.351890 0.6548350 0.2375602 0.2521257 0.5751375
2 versicolor 1.895540 0.3868576 0.9083370 -0.6792238 0.6050314
3 virginica 0.699883 0.3303370 0.9455356 -0.1697527 0.7652193
如冻糕所建议的,您不需要plyr::ddply()
,可以使用do.call(rbind, by(df, df$Species, getCoef))
希望这会有所帮助!