generic_user
generic_user

Reputation: 3572

Making a vector from list elements in R

I've got a list of lists of bootstrap statistics from a function that I wrote in R. The main list has the 1000 bootstrap iterations. Each element within the list is itself a list of three things, including fitted values for each of the four variables ("fvboot" -- a 501x4 matrix).

I want to make a vector of the values for each position on the grid of x values, from 1:501, and for each variable, from 1:4.

For example, for the ith point on the xgrid of the jth variable, I want to make a vector like the following:

        vec = bootfits$fvboot[[1:1000]][i,j]

but when I do this, I get:

recursive indexing failed at level 2

googling around, i think I understand why R is doing this. but I'm not getting an answer for how I can get the ijth element of each fvboot matrix into a 1000x1 vector.

help would be much appreciated.

Upvotes: 10

Views: 16222

Answers (3)

Swarit Jasial
Swarit Jasial

Reputation: 61

Use unlist() function in R. From example(unlist),

unlist(options())
unlist(options(), use.names = FALSE)

l.ex <- list(a = list(1:5, LETTERS[1:5]), b = "Z", c = NA)
unlist(l.ex, recursive = FALSE)
unlist(l.ex, recursive = TRUE)

l1 <- list(a = "a", b = 2, c = pi+2i)
unlist(l1) # a character vector
l2 <- list(a = "a", b = as.name("b"), c = pi+2i)
unlist(l2) # remains a list

ll <- list(as.name("sinc"), quote( a + b ), 1:10, letters, expression(1+x))
utils::str(ll)
for(x in ll)
  stopifnot(identical(x, unlist(x)))

Upvotes: 6

anoop
anoop

Reputation: 81

You can extract one vector at a time using sapply, e.g. for i=1 and j=1:

i <- 1
j <- 1
vec <- sapply(bootfits, function(x){x$fvboot[i,j]})

sapply carries out the function (in this case an inline function we have written) to each element of the list bootfits, and simplifies the result if possible (i.e. converts it from a list to a vector).

To extract a whole set of values as a matrix (e.g. over all the i's) you can wrap this in another sapply, but this time over the i's for a specified j:

j <- 1
mymatrix <- sapply(1:501, function(i){
    sapply(bootfits, function(x){x$fvboot[i,j]})
})

Warning: I haven't tested this code but I think it should work.

Upvotes: 2

user2503795
user2503795

Reputation: 4155

This would be easier if you give a minimal example object. In general, you can not index lists with vectors like [[1:1000]]. I would use the plyr functions. This should do it (although I haven't tested it):

require("plyr")
laply(bootfits$fvboot,function(l) l[i,j])

If you are not familiar with plyr: I always found Hadley Wickham's article 'The split-apply-combine strategy for data analysis' very useful.

Upvotes: 4

Related Questions