1

Say I have a list, preds, that contains 3 different sets of predictions based on unique models.

set.seed(206)
preds <- list(rnorm(1:100), rnorm(1:100), rnorm(1:100))

I am having trouble iterating through the list and creating a new list. I want a list of new vectors that are composed of the corresponding index in the other vectors. So for example, I can get the first element in each vector of the list using sapply() like this:

sapply(preds, "[[", 1)

Which works well, but I cannot figure out how to iterate through each element in each vector to construct a new list. I want something like this (doesn't work):

sapply(preds, "[[", 1:100)

Using the above seed and preds list, my desired output would be something like:

first_element <- sapply(preds, "[[", 1)
second_element <- sapply(preds, "[[", 2)
third_element <- sapply(preds, "[[", 3)
desired_result <- rbind(first_element, second_element, third_element) 

But for all elements in the list, which in this example is 100.

Please let me know if this is not clear, and I appreciate any help!

Raphael K
  • 2,265
  • 1
  • 16
  • 23

2 Answers2

4

We need to use [

res <- sapply(preds, `[`, 1:3 )
all.equal(res, desired_result, check.attributes=FALSE)
#[1] TRUE
akrun
  • 874,273
  • 37
  • 540
  • 662
1

Here's an alternative approach:

nth_element <- function(dat, n){

   res <- sapply(dat, "[[", n)

   res

}

res2 <- do.call(rbind, lapply(c(1:3), function(x) nth_element(dat = preds, n = x)))

Borrowing akrun's check code:

all.equal(res2, desired_result, check.attributes=FALSE)
russodl
  • 96
  • 2
  • Very nice, this is where my mind was originally going, but I didn't quite get there. I had basically identical code but was trying a for() loop instead of just creating a custom function. I appreciate the additional solution. – Raphael K May 11 '16 at 19:38