Knut Hansen
2015-Feb-20 12:18 UTC
[R] How do I access a specific element of a multi-dimensional list
Dear list, Let's say I have setup the following list: a = c(2, 3, 5) b = c("aa", "bb", "cc") c = c(TRUE, FALSE, TRUE) x = list(a, b, c) I want to access the first second dimension element of each first dimension element so that the result is something like: (2, "aa", TRUE) In my real life problem the list is about 350 elements in the first dimension so the solution must handle that. Sincerely Knut Hansen
jim holtman
2015-Feb-20 17:34 UTC
[R] How do I access a specific element of a multi-dimensional list
try this:> a = c(2, 3, 5) > b = c("aa", "bb", "cc") > c = c(TRUE, FALSE, TRUE) > > x = list(a, b, c) > x[[1]] [1] 2 3 5 [[2]] [1] "aa" "bb" "cc" [[3]] [1] TRUE FALSE TRUE> sapply(x, '[[', 1)[1] "2" "aa" "TRUE">Jim Holtman Data Munger Guru What is the problem that you are trying to solve? Tell me what you want to do, not how you want to do it. On Fri, Feb 20, 2015 at 7:18 AM, Knut Hansen <knut.hansen at uit.no> wrote:> Dear list, > > Let's say I have setup the following list: > a = c(2, 3, 5) > b = c("aa", "bb", "cc") > c = c(TRUE, FALSE, TRUE) > > x = list(a, b, c) > > I want to access the first second dimension element of each first dimension > element so that the result is something like: > (2, "aa", TRUE) > > In my real life problem the list is about 350 elements in the first dimension > so the solution must handle that. > > Sincerely > Knut Hansen > > ______________________________________________ > R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see > 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.
JS Huang
2015-Feb-20 21:52 UTC
[R] How do I access a specific element of a multi-dimensional list
Hi, Jim's answer is neat. There is an issue on the result. All are characters even though some are numeric or logic. The following implementation retains the variable type.> x[[1]] [1] 2 3 5 [[2]] [1] "aa" "bb" "cc" [[3]] [1] TRUE FALSE TRUE> getFirstfunction(aList) { result <- list() for (i in 1:length(aList)) { result <- c(result, aList[[i]][1]) } return(result) }> getFirst(x)[[1]] [1] 2 [[2]] [1] "aa" [[3]] [1] TRUE>-- View this message in context: http://r.789695.n4.nabble.com/How-do-I-access-a-specific-element-of-a-multi-dimensional-list-tp4703596p4703622.html Sent from the R help mailing list archive at Nabble.com.