R data.table loop subset by factor and do lm()

前端 未结 3 443
猫巷女王i
猫巷女王i 2021-01-13 12:03

I am trying to create a function or even just work out how to run a loop using data.table syntax where I can subset the table by factor, in this case the id variable, then r

3条回答
  •  花落未央
    2021-01-13 12:48

    > df <- data.frame(id = letters[1:3], 
                       +                  cyl = sample(c("a","b","c"), 30, replace = TRUE),
                       +                  factor = sample(c(TRUE, FALSE), 30, replace = TRUE),   
                       +                  hp = sample(c(20:50), 30, replace = TRUE))
    > by(df,df$id,function(x) lm(hp ~ cyl + factor, data = x))
    df$id: a
    
    Call:
      lm(formula = hp ~ cyl + factor, data = x)
    
    Coefficients:
      (Intercept)         cylb         cylc   factorTRUE  
    41.571        4.143       -3.429       -5.571  
    
    ------------------------------------------------------------------------------------------ 
      df$id: b
    
    Call:
      lm(formula = hp ~ cyl + factor, data = x)
    
    Coefficients:
      (Intercept)         cylb         cylc   factorTRUE  
    46.040       -1.133      -19.467       -7.720  
    
    ------------------------------------------------------------------------------------------ 
      df$id: c
    
    Call:
      lm(formula = hp ~ cyl + factor, data = x)
    
    Coefficients:
      (Intercept)         cylc   factorTRUE  
    31.850        3.917       -8.200  
    
        enter code here
    

提交回复
热议问题