【问题标题】:mapply with arguments as two lists (one formulas, one vectors)将参数映射为两个列表(一个公式,一个向量)
【发布时间】:2014-01-12 22:39:11
【问题描述】:

我正在尝试使用mapplyt.test 应用于两个参数列表。第一个列表formulas 包含三个公式,第二个列表periods 包含三个向量,它们是my.data 的子集,我使用MoreArgs 参数传递。

我可以使用for 循环(也在下方)手动执行t.tests,但我无法弄清楚为什么我的mapply 使用失败。这不是使用mapply的正确时间吗?

# similar data
my.data <- data.frame(CAR1=rnorm(150),
                      CAR2=rnorm(150),
                      CAR3=rnorm(150),
                      period=rep(1:3, each=50),
                      treated=rep(1:2, times=75)
                      )

# two lists to pass as arguments to `t.test()`
# `subset`
periods <- list(my.data$period == 1,
                my.data$period <= 2,
                my.data$period <= 3
                )
# `formula`
formulas <- list(CAR1 ~ treated,
                 CAR2 ~ treated,
                 CAR3 ~ treated
                 )

# manual solution works
ttests <- list()
for (i in 1:3) {
    ttests[[i]] <- t.test(formulas[[i]], 
                          data=my.data, 
                          subset=periods[[i]]
                          )
}

# but `mapply` fails
ttest <- mapply(FUN=t.test, 
                formula=formulas, 
                subset=periods, 
                MoreArgs=list(data=my.data),
                SIMPLIFY=FALSE
                )

# with error "Error in eval(expr, envir, enclos) : object 'dots' not found"

【问题讨论】:

    标签: r mapply


    【解决方案1】:

    如果根据period 拆分data.frame,则不需要periods 对象。

    split.my.data <- split(my.data, f = my.data$period)
    
    mapply(FUN = function(x, y) {
      t.test(x, data = y)  
    }, x = formulas, y = split.my.data, SIMPLIFY = FALSE)
    
    [[1]]
    
        Welch Two Sample t-test
    
    data:  CAR1 by treated
    t = -0.7051, df = 44.861, p-value = 0.4844
    alternative hypothesis: true difference in means is not equal to 0
    95 percent confidence interval:
     -0.9277752  0.4466579
    sample estimates:
    mean in group 1 mean in group 2 
          0.1650074       0.4055661 
    
    
    [[2]]
    ... # output truncated
    

    编辑

    如果您想根据== 以外的逻辑运算符对因子进行子集化,我会像这样创建一个“拆分列表”。

    split.my.data <- sapply(periods, FUN = function(x, my.data) my.data[x, ], 
           my.data = my.data, simplify = FALSE)
    

    【讨论】:

    • 谢谢!好点子!但是如果我的样本周期不是互斥的呢? (我会改进我的例子。)你还会建议这种方法吗?有没有办法将subset 作为列表传递?
    • 我添加了另一个示例,说明我将如何构建一个列表以提供给mapply
    猜你喜欢
    • 2010-09-19
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多