【问题标题】:Generating linear models for several columns in a dataframe at once [duplicate]一次为数据框中的几列生成线性模型[重复]
【发布时间】:2019-03-28 06:09:15
【问题描述】:

我有以下数据框:

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 函数)?我的实际数据框有更多的行和列。谢谢!

【问题讨论】:

  • 这两个链接都会为您提供自动解决方案。第一个链接告诉你如何使用sprintf来构造公式并使用lm的“mlm”支持;第二个链接专门用于简单的线性回归,使用我的函数general_paired_simpleLM

标签: r


【解决方案1】:

试试

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 必须是数据框。

【讨论】:

  • 我实际上有超过 50 列要执行此操作。除了使用cbind(A, B, C),有没有办法可以在df[, 2:4] 上执行此操作?
  • @DavidMoore 你可以做lm(as.matrix(df[, 2:50]) ~ Index, data = df)。抱歉回复晚了。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 2015-03-21
    相关资源
    最近更新 更多