r - Extracting matrices from list of list sub-elements keeping the list/sub-list indices for the matrix -
new r , hoping find elegant way of solving seems simple problem. context of problem follows: running regressions set of companies @ rolling periods of time. storing summary of each regression in list of lists. so, example:
results[[i]][[t]] = summary(lm(y~x))
, y
, x
associated vectors company i
@ time t
. extract matrices sigma
results
such that:
sigma[i,t] = results [[i]] [[t]]$sigma
clearly can nested loops, seems there must simple way of extracting matrix in 1 step lapply, sapply, etc. have seen similar problems answered throughout web , blog, have not been able correctly adapt them problem. twist of entries in results 'null', happens when there insufficient data specific company @ specific time run regression.
any or direction appreciated.
you can use lapply
, do.call
:
first create sample data:
results <- list() (i in 1:5){ results[[i]] <- list() (t in 1:3){ x <- sample(10) y <- sample(10) results[[i]][[t]] <- summary(lm(x~y)) } }
then create new matrix sigmas:
sigma <- do.call(rbind, lapply(results, function(x)lapply(x, function(y)y$sigma))) colnames(sigma) <- paste("t", 1:ncol(sigma), sep="") rownames(sigma) <- paste("c", 1:nrow(sigma), sep="")
the matrix looks follows:
> sigma t1 t2 t3 c1 2.302831 3.201325 3.154122 c2 3.066436 3.179956 3.146427 c3 2.752409 3.189946 2.819306 c4 3.211249 3.210777 2.983795 c5 3.179956 3.179956 2.340034
Comments
Post a Comment