Hi, I was trying to use lapply to create a matrix from a list: uu <- list() uu[[1]] <- c(1,2,3) uu[[2]] <- c(3,4,5) The output I desire is a matrix with 2 rows and 3 columns, so I try: xx <- lapply(uu,rbind) Obviously, I'm not doing something right, but what!? [[alternative HTML version deleted]]
Hi, the output of lapply() is a list; see ?lapply and ?sapply. # if you know the length of your list in advance, # this definition is better: uu <- vector("list", 2) # list elements uu[[1]] <- c(1,2,3) uu[[2]] <- c(3,4,5) # some options to achieve what you want: matrix(unlist(uu), 2, 3, T) do.call(rbind, uu) t(sapply(uu, I)) HTH, Denes> Hi, > > I was trying to use lapply to create a matrix from a list: > > uu <- list() > uu[[1]] <- c(1,2,3) > uu[[2]] <- c(3,4,5) > > The output I desire is a matrix with 2 rows and 3 columns, so I try: > > xx <- lapply(uu,rbind) > > Obviously, I'm not doing something right, but what!? > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >
On 14-11-2013, at 16:20, Brian Smith <bsmith030465 at gmail.com> wrote:> Hi, > > I was trying to use lapply to create a matrix from a list: > > uu <- list() > uu[[1]] <- c(1,2,3) > uu[[2]] <- c(3,4,5) > > The output I desire is a matrix with 2 rows and 3 columns, so I try: > > xx <- lapply(uu,rbind) > > Obviously, I'm not doing something right, but what!?do.call(rbind,uu) Berend
Hello, You are applying rbind to each element of the list, not rbinding it with the others. Try instead do.call(rbind, uu) Hope this helps, Rui Barradas Em 14-11-2013 15:20, Brian Smith escreveu:> Hi, > > I was trying to use lapply to create a matrix from a list: > > uu <- list() > uu[[1]] <- c(1,2,3) > uu[[2]] <- c(3,4,5) > > The output I desire is a matrix with 2 rows and 3 columns, so I try: > > xx <- lapply(uu,rbind) > > Obviously, I'm not doing something right, but what!? > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >