Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a vector from list elements in R

Tags:

list

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.

like image 823
generic_user Avatar asked Dec 06 '12 21:12

generic_user


2 Answers

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)))
like image 102
Swarit Jasial Avatar answered Nov 15 '22 22:11

Swarit Jasial


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.

like image 23
anoop Avatar answered Nov 15 '22 22:11

anoop