How do I store “arrays” of statistical models?

后端 未结 3 1175
青春惊慌失措
青春惊慌失措 2020-12-30 05:29

Is there an R data structure into which I can store a number of lm or lmer or gam objects? J has boxed arrays, and one c

相关标签:
3条回答
  • 2020-12-30 05:42

    Use [[ to access the list elements:

    library(mgcv)
    set.seed(0) ## simulate some data... 
    dat <- gamSim(1,n=400,dist="normal",scale=2)
    
    mods <- vector(mode = "list", length = 3)
    for(i in seq_along(mods)) {
        mods[[i]] <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat)
    }
    

    Giving:

    > str(mods, max = 1)
    List of 3
     $ :List of 43
      ..- attr(*, "class")= chr [1:3] "gam" "glm" "lm"
     $ :List of 43
      ..- attr(*, "class")= chr [1:3] "gam" "glm" "lm"
     $ :List of 43
      ..- attr(*, "class")= chr [1:3] "gam" "glm" "lm"
    
    0 讨论(0)
  • 2020-12-30 05:50

    You need the [[ operator for lists, try

    testlist[[1]] <- subject1.2008.gam
    

    The other usual tip is that you may want to pre-allocate if you know how many elements you may have, I often do

    testlist <- vector(mode="list", length=N)
    

    for a given N.

    0 讨论(0)
  • 2020-12-30 06:00

    The other answers show how to use an index and [[ ]] but you can also do something like

    x1  <- 1:10  ; y1  <-  30*x1 + rnorm(10)
    x2  <- rnorm(20)  ; y2  <- 30*x2 + 100 + rnorm(20)
    lm1 <- lm(y1 ~ x1); lm2 <- lm(y2 ~ x2) 
    
    testlist <- list( A = lm1, Z = lm2 ) 
    testlist$Z
    testlist$Z$model$y2
    
    0 讨论(0)
提交回复
热议问题