Search code examples
rlistapplylapplysapply

How to subset a list in R?


In the below code, I create a list with the bootTest() function, where 5 samples are extracted from the lung dataset of the survival package. I would like to extract the first iteration in its entirety, as shown in tmp() function below. That tmp() code is awfully goofy. Is there a clean way to extract, as a dataframe and using the same column headers as the lung dataframe, the results of iteration 1 (and 2, then 3, and so on) from bootTest()?

Code:

library(survival)
data(lung)

bootTest <- sapply(
  1:5,
  function(i) {
    sample_data <- lung[sample(nrow(lung), replace = TRUE), ]
    return(sample_data)
  }
)

tmp <- data.frame(bootTest[1,1],
                  bootTest[2,1],
                  bootTest[3,1],
                  bootTest[4,1],
                  bootTest[5,1],
                  bootTest[6,1],
                  bootTest[7,1],
                  bootTest[8,1],
                  bootTest[9,1],
                  bootTest[10,1]
                  )

Solution

  • In base R you can do:

    data.frame(bootTest[,1])
    

    all.equal(data.frame(bootTest[,1]), tmp)
    [1] TRUE