Creating a vector from list items in R

I have a list of load statistics lists from a function that I wrote in R. There are 1000 bootstrap iterations in the main list. Each item in the list itself is a list of three things, including the set values ​​for each of the four variables ("fvboot" - 501x4 matrix).

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

For example, for the ith xgrid point of the jth variable, I want to make a vector as follows:

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 does this. but I do not get an answer for how I can get the ijth element of each fvboot matrix into a 1000x1 vector.

Help

would be greatly appreciated.

+7
source share
3 answers

It will be easier if you give a minimal approximate object. In general, you cannot index lists with vectors like [[1:1000]] . I would use plyr functions. This should do it (although I have not tested it):

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

If you are new to plyr : I always found Hadley Wickham's article Split-apply-comb Strategy for Data Analysis . very useful.

+4
source

Use the 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))) 
+4
source

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

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

sapply performs a function (in this case, the built-in function that we wrote) for each element of the list's loading frames, and, if possible, simplifies the result (i.e., converts it from the list to a vector).

To extract the entire set of values ​​in the form of a matrix (for example, above all i-th ones), you can wrap it in another way, but this time by i for the specified j:

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

Warning: I have not tested this code, but I think it should work.

+1
source

All Articles