一次为数据框中的几列生成线性模型

时间:2018-10-23 22:22:26

标签: r

我有以下数据框:

Index <- seq.int(1:10)
A <- c(5, 5, 3, 4, 3, 3, 2, 2, 4, 3)
B <- c(10, 11, 12, 12, 12, 11, 13, 13, 14, 13)
C <- c(7, 6, 7, 7, 6, 5, 6, 5, 5, 4)
df <- data.frame(Index, A, B, C)
> df
      Index A  B C
 [1,]     1 5 10 7
 [2,]     2 5 11 6
 [3,]     3 3 12 7
 [4,]     4 4 12 7
 [5,]     5 3 12 6
 [6,]     6 3 11 5
 [7,]     7 2 13 6
 [8,]     8 2 13 5
 [9,]     9 4 14 5
[10,]    10 3 13 4

我想生成以下三个线性模型:

lm(df$A ~ df$Index)
lm(df$B ~ df$Index)
lm(df$C ~ df$Index)

是否有一种方法可以一步一步快速有效地执行此操作(可能使用lapply函数)?我的实际数据框有更多的行和列。谢谢!

2 个答案:

答案 0 :(得分:0)

尝试

df <- data.frame(Index, A, B, C) 
lm(cbind(A, B, C) ~ Index, data = df)
#Call:
#lm(formula = cbind(A, B, C) ~ Index, data = df)

#Coefficients:
#             A        B        C      
#(Intercept)   4.6000  10.2667   7.4000
#Index        -0.2182   0.3333  -0.2909

请注意,df必须是一个数据框。

答案 1 :(得分:0)

您也可以使用tidyverse这样的方法:

library(tidyverse)
df %>% 
  gather(Variables, Value, A:C) %>% 
  split(.$Variables) %>% 
  map(~ lm(Value~Index, data = .)) %>% 
  map(summary)