我已经使用lm()对R中的数据集执行了多元回归分析,并且我能够使用下面的函数提取一年中每一天的系数。我还想提取一年中每一天的R2,但这似乎不是以相同的方式工作的。
这个问题和:Print R-squared for all of the models fit with lmList几乎是一样的,但是当我尝试这个的时候,我得到了“错误:$ operator对于原子向量是无效的”。如果可能的话,我也想把它包含在同一个函数中。如何以这种方式提取每个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)```
发布于 2019-07-01 15:01:29
重点是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))
希望这能有所帮助!
https://stackoverflow.com/questions/56837596
复制相似问题