【问题标题】:How can I use the original argument name in a function when using an apply function in R?在 R 中使用 apply 函数时,如何在函数中使用原始参数名称?
【发布时间】:2016-04-30 23:49:36
【问题描述】:

每当我使用应用函数时,在匿名函数中使用虚拟变量都会导致在内部使用该虚拟变量的名称。在处理结果列表时,如何在内部使用原始变量名以避免复杂化?

以下是描述我的意思的示例:

set.seed(314)

df <- data.frame(response = rnorm(500),
                Col1 = rnorm(500),
                Col2 = rnorm(500),
                Col3 = rnorm(500),
                Col4 = rnorm(500))

> apply(df[, 2:5], 2, function(x) lm(response ~ x, data = df))
$Col1

Call:
lm(formula = response ~ x, data = df)

Coefficients:
(Intercept)            x  
   0.074452     0.007713  


$Col2

Call:
lm(formula = response ~ x, data = df)

Coefficients:
(Intercept)            x  
    0.06889      0.07663  


$Col3

Call:
lm(formula = response ~ x, data = df)

Coefficients:
(Intercept)            x  
    0.07401      0.03512  


$Col4

Call:
lm(formula = response ~ x, data = df)

Coefficients:
(Intercept)            x  
   0.073668    -0.001059  

我希望上面的每个线性回归在每个回归中都使用名称 Col1、Col2 等,而不是 x。此外,当我使用 apply 函数时,我正在寻找一种在任何情况下(不仅仅是线性回归)使用原始名称的通用方法。

【问题讨论】:

    标签: r


    【解决方案1】:

    一种方法是分两步完成:

    1) 首先按照您的操作运行回归 2)替换系数名称和公式

    l <- lapply(df[, 2:5], function(x) lm(response ~ x, data = df))
    for (i in 1:length(l)) {
      names(l[[i]]$coefficients)[2] <- names(l)[i]
      l[[i]]$call <- gsub('x', names(l)[i], l[[i]]$call)
    }
    

    结果输出如下:

    $Col1
    
    Call:
    c("lm", "response ~ Col1", "df")
    
    Coefficients:
    (Intercept)         Col1  
       -0.04266     -0.07508  
    
    
    $Col2
    
    Call:
    c("lm", "response ~ Col2", "df")
    
    Coefficients:
    (Intercept)         Col2  
       -0.04329      0.02403  
    
    
    $Col3
    
    Call:
    c("lm", "response ~ Col3", "df")
    
    Coefficients:
    (Intercept)         Col3  
       -0.04519     -0.03300  
    
    
    $Col4
    
    Call:
    c("lm", "response ~ Col4", "df")
    
    Coefficients:
    (Intercept)         Col4  
       -0.04230     -0.04506  
    

    【讨论】:

    • 谢谢,但公式调用中仍然有 x 而不是 Col1、Col2 等。
    • 编辑了答案来解决这个问题......你只需要抓住call字段并修改它。
    • 谢谢,但有没有办法在每种情况下自动执行此操作?就像我想不仅在它出现的每个地方用变量手动替换 x ,而且无论我正在使用什么都自动执行它。我的问题是关于如何做到这一点。不仅仅是如何在线性回归中做到这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    相关资源
    最近更新 更多