使用mapply在两个列表列表中查找anova结果

时间:2016-02-03 21:20:22

标签: r list anova mapply

我有两个嵌套的lm结果列表(完整模型和简化模型),它们列出了三个结果变量。我想使用列表将anova应用于模型的每个完整和简化版本(零假设显着性测试)。我试图给出一个简化的例子,感谢TRinker's DFgen来说明

df1 <-DFgen()
df1
    id   group hs.grad  race gender age m.status   political n.kids income score time1 time2  time3
    1   ID.1 control     yes black   male  24    never    democrat      2 142000 -1.40 88.44 91.09  93.61
    2   ID.2   treat     yes black   male  32  married    democrat      2  81000  0.16 48.34 48.58  48.58
    3   ID.3   treat     yes white   male  30  married independent      1 131000  0.87  7.04  8.31   9.78
    4   ID.4 control      no black female  37    never independent      1  11000 -0.03 25.89 27.24  31.70
    5   ID.5 control      no black female  18    never  republican      2  62000  0.95  1.36  1.96   6.54
    6   ID.6   treat     yes asian   male  31 divorced  republican      1  65000  1.13 98.73 99.98 103.43
    7   ID.7   treat     yes white female  19 divorced    democrat      1 142000  0.39 25.75 29.11  29.21
    8   ID.8   treat      no black female  31  married  republican      0  73000  0.38 57.09 61.89  66.27
    9   ID.9 control     yes black   male  31  married    democrat      2 127000 -0.25 40.11 42.81  45.67
    10 ID.10 control     yes white   male  30  married       other      2 139000  0.50 26.02 28.42  31.56

    df1 <-DFgen()
    df2 <- df1[(df1$gender=="female"),]
    #list of all 3 times
    times1 <- df1[, c("time1", "time2", "time3")]
    times2 <- df2[, c("time1", "time2", "time3")]

    #function for model1, no family variables
    nf.lm <- function(x, y, db){
    lm(x~age+income+y, data=db) 
    }

    #Hypot 1: both sexes, group as predictor, lapply all 3 time variables 
    h1.res <- lapply(times1, y=df1$group, db=df1, nf.lm)

    #Hypot 2: female only, group as predictor, lapply all 3 time variables 
    h2.res <- lapply(times2, y=df2$group, db=df2, nf.lm)

    #make list of model results
    m.res <- list(h1.res, h2.res)

    #Reduced models for comparison with H1 and H2
    nf.lm.red <- function(x, db){
    lm(x~age+income, data=db)   
    }

    h1.red <- lapply(times1, db=df1, nf.lm.red)
    h2.red <- lapply(times2, db=df2, nf.lm.red)

    #make list for reduced models
    m.red <- list(h1.red, h2.red)

    #apply anova to full and reduced model for each time outcome
    mapply(mapply(function(red, res) { 
        anova(red, res, test="F")   
    }, red=m.red, res=m.res))

我收到了消息,

    Error in UseMethod("anova") : 
  no applicable method for 'anova' applied to an object of class "list"

我想我可能需要在mapply中嵌套另一个函数吗?在我的实际数据中,我有2个列表,每个列表包含3组lm结果,所以任何帮助都将非常感激。如果这是一个提出简单问题的复杂方式,我很抱歉,但我还是新的!

1 个答案:

答案 0 :(得分:0)

也许:

lapply(seq_along(m.red), 
       FUN=function(x) lapply( seq_along(m.red[[x]]), 
                               FUN= function(y) anova(m.red[[x]][[y]],  m.res[[x]][[y]], test="F")
       )
)