【发布时间】:2020-10-28 13:42:11
【问题描述】:
我的数据框中有几个变量(例如:a、b、c、d),我通过此代码(变量 a 的示例)通过季节线性模型参数(截距、斜率和 rSquared)获得:
lm_results_season_a<- ddply(dataframe1, "Season", function(x) {
model <- summary(lm(y ~ a, data = x))
Intercept<- model$coefficients[1,1]
Slope<- model$coefficients[2,1]
rSquared <- model$r.squared
data.frame(Intercept, Slope, rSquared)
})
我的问题是我有太多的变量,并且对每个变量再次重复此代码会占用大量空间。 例如,我必须为变量 b 编写相同的代码
lm_results_season_b<- ddply(dataframe1, "Season", function(x) {
model <- summary(lm(y ~ b, data = x))
Intercept<- model$coefficients[1,1]
Slope<- model$coefficients[2,1]
rSquared <- model$r.squared
data.frame(Intercept, Slope, rSquared)
})
并继续对其余变量重复相同的代码。所以我尝试创建一个函数,我不必再次重复所有这些代码,而只是调用一个可以进行所有计算并给我我正在寻找的数据框的函数。 我尝试了这段代码,之前在其中定义了变量,然后将它们添加到函数中:
variable1 <- dataframe1$y
variable2 <- dataframe1$a
LM_coef <- function(data, variable1, variable2){
lm_results_season<- ddply(data, "Season", function(x) {
model <- summary(lm(variable1 ~ variable2, data = x))
Intercept<- model$coefficients[1,1]
Slope<- model$coefficients[2,1]
rSquared <- model$r.squared
data.frame(Intercept,Slope, rSquared)
})
return(lm_results_season)
}
但这并没有按我的意愿工作。不是按季节给我变量“a”的线性回归参数,而是只给我变量“a”作为一个整体的线性回归参数,而不是按季节。
知道函数中发生了什么或如何修改此函数吗?
【问题讨论】:
-
可以直接传公式
LM_coef <- function(data, formula){ lm_results_season<- ddply(data, "Season", function(x) { model <- summary(lm(formula = formula, data = x)) ; .... }) ; return(lm_results_season) } ; LM_coef(data = dataframe1, formula = y ~ a) -
我试过了,但它仍然给我与我发布的函数相同的输出。谢谢你的时间。
标签: r function dataframe linear-regression plyr