【问题标题】:Creating a function out of a dataframe with a function使用函数从数据框创建函数
【发布时间】: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 &lt;- function(data, formula){ lm_results_season&lt;- ddply(data, "Season", function(x) { model &lt;- summary(lm(formula = formula, data = x)) ; .... }) ; return(lm_results_season) } ; LM_coef(data = dataframe1, formula = y ~ a)
  • 我试过了,但它仍然给我与我发布的函数相同的输出。谢谢你的时间。

标签: r function dataframe linear-regression plyr


【解决方案1】:

您是否绑定到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 获得的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    相关资源
    最近更新 更多