[R] Reducing the "dimension" of a list object
Uwe Ligges
ligges at statistik.tu-dortmund.de
Fri Dec 11 11:40:39 CET 2009
Bogaso wrote:
> Please consider following code :
>
> set.seed(1)
> res <- vector("list")
> for (i in 1:5) {
> res1 <- vector("list")
> res1[[1]] <- letters[1:5]
> res1[[2]] <- rnorm(5)
> res1[[3]] <- rnorm(5); res[[i]] <- res1 }
> res[[1]]
>
> # Now I want to reduce the dimension of "res" through creating a data frame
> like that
> mat <- data.frame(nrow=5, ncol=2)
> for (i in 1:5) {
> mat[i,1] <- res[[i]][[1]][1]
> mat[i,2] <- res[[i]][[2]][1] }; mat
>
> Here I am looking for more "efficient" code by avoiding the loop. Is there
> any smart way to do that ?
Perhaps directly rewritten without thinking:
mat <- data.frame(
letters = sapply(res, "[[", c(1,1)),
numbers = sapply(res, "[[", c(2,1)))
which should be roughly 2.5 times faster.
Uwe Ligges
> Thanks,
More information about the R-help
mailing list