代码之家  ›  专栏  ›  技术社区  ›  Alexis Drakopoulos

在函数内部或外部运行lm()时会产生不同的结果

r
  •  0
  • Alexis Drakopoulos  · 技术社区  · 7 年前

    功能:

    linear_regression <- function(dataframe, target) {
    
      model = lm(target ~ .,data = dataframe)
    
      return(model)
    
    }
    

    我使用的数据帧名为test2,目标列名为 DP_POWER- DP_POWER

    在外面运行:

    lm(test2$`DP_POWER- DP_POWER` ~ .,data = test2)
    

    结果

    Call:
    lm(formula = test2$`DP_POWER- DP_POWER` ~ ., data = test2)
    
    Coefficients:
                                      (Intercept)  `OTHER VARIABLE`  
                                         1154.789                                          1.134  
    

    通过调用在函数内部运行此命令:

    linear_regression(dataframe = test2, target = test2$`DP_POWER- DP_POWER`)
    

    Call:
    lm(formula = target ~ ., data = dataframe)
    
    Coefficients:
                                      (Intercept)                           `DP_POWER- DP_POWER`  
                                       -1.807e-10                                      1.000e+00  
    `OTHER VARIABLE`  
                                       -1.552e-15  
    

    您可以清楚地看到,出于某种原因运行我的用户自定义函数会计算DP\u POWER-DP\u POWER,而在控制台中运行它则不会。

    为什么会发生这种情况?我该如何防止?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Alexis Drakopoulos    7 年前

    当他建议使用作为公式(粘贴())

    linear_regression <- function(dataframe, target) {
    
      model = lm(as.formula(paste(target, '~ .')),data = dataframe)
    
      return(model)
    
    }