Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 使用函数从数据帧创建函数_R_Function_Dataframe_Linear Regression_Plyr - Fatal编程技术网

R 使用函数从数据帧创建函数

R 使用函数从数据帧创建函数,r,function,dataframe,linear-regression,plyr,R,Function,Dataframe,Linear Regression,Plyr,我的数据框中有几个变量(例如:a、b、c、d),我通过以下代码(变量a的示例)按季节获取线性模型参数(截距、斜率和rSquared): lm\u结果\u季节\u a您是否绑定到plyr包?否则,您可以使用更高级和最新的purr软件包,始终从tidyverse世界下载 在这里,我们可以创建一个函数,在其中插入数据框数据、线性模型变量1和变量2的两个变量,以及拆分列拆分变量(在您的案例中为“季节”) 为了获得 # cyl Intercept Slope rSquared # 1

我的数据框中有几个变量(例如:a、b、c、d),我通过以下代码(变量a的示例)按季节获取线性模型参数(截距、斜率和rSquared):


lm\u结果\u季节\u a您是否绑定到
plyr
包?否则,您可以使用更高级和最新的
purr
软件包,始终从
tidyverse
世界下载

在这里,我们可以创建一个函数,在其中插入数据框
数据
、线性模型
变量1
变量2
的两个变量,以及拆分列
拆分变量
(在您的案例中为“季节”)

为了获得

#   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\u结果\u季节\u a

中获得的值。您是否绑定到
plyr
包?否则,您可以使用更高级和最新的
purr
软件包,始终从
tidyverse
世界下载

在这里,我们可以创建一个函数,在其中插入数据框
数据
、线性模型
变量1
变量2
的两个变量,以及拆分列
拆分变量
(在您的案例中为“季节”)

为了获得

#   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\u seasure\u a

中获得的值,如果我尝试过,它可能会直接通过公式
lm_coef,但它仍然提供与我发布的函数相同的输出。谢谢你的时间。如果我试过的话,也许可以直接传递公式,但它仍然提供与我发布的函数相同的输出。谢谢你抽出时间。
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)
}
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"))
}
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