使用函数从数据框中创建函数

Creating a function out of a dataframe with a function

我的数据框中有几个变量(例如: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)
})

我的问题是我有太多变量,并且为每个变量重复此代码需要很多 space。 例如,我必须为变量 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”的线性回归参数,而不是按季节。

知道函数中发生了什么或如何修改此函数吗?

您是否绑定了 plyr 包?否则,您可以使用更高级和最新的 purrr 包,总是来自 tidyverse 世界。

在这里我们可以创建一个函数,我们可以在其中插入数据框 data、线性模型的两个变量 variable1variable2,以及拆分列 split_var (在你的例子中是“季节”)。

LM_coef <- function(data, variable1, variable2, split_var){
  require(purrr)
  
  data %>%
    split(.[[split_var]]) %>%
    map(~summary(lm(eval(as.name(variable1)) ~ eval(as.name(variable2)), data = .x))) %>%
    map_dfr(~cbind(as.data.frame(t(as.matrix(coef(.)[1:2,1]))), .$r.squared), .id = split_var) %>% 
    setNames(c(split_var, "Intercept", "Slope", "rSquared"))
}

例子

使用mtcars数据集,我们可以

LM_coef(mtcars, "hp", "mpg", "cyl")

为了获得

#   cyl Intercept     Slope   rSquared
# 1   4  147.4315 -2.430092 0.27405583
# 2   6  164.1564 -2.120802 0.01614624
# 3   8  294.4974 -5.647887 0.08044919

这等于您从初始函数中获得的值 lm_results_season_a