Hi, I have a list of 100, each list has 20 elements, and I would like to select the first 7 elements in each list. Let's take the alphabet as an example. x <- lapply(1:100, function(i) sample(LETTERS)) I tried x[[1:7]], but it doesn't work. Can anyone enlighten me on how to do such selections? Thank you. Kang Min
Kang Min wrote:> Hi, > > I have a list of 100, each list has 20 elements, and I would like to > select the first 7 elements in each list. > Let's take the alphabet as an example. > > x <- lapply(1:100, function(i) sample(LETTERS)) > > I tried x[[1:7]], but it doesn't work. Can anyone enlighten me on how > to do such selections?"[" is a function, and you want to use it on each element of the list, so... lapply(x, "[", c(1:7))
> "[" is a function, and you want to use it on each element of the list, > so... > > lapply(x, "[", c(1:7))and the call to c() is of course not necessary, since ":" will generate a vector.
Thanks a lot, it works! On May 23, 3:10?pm, Erik Iverson <er... at ccbr.umn.edu> wrote:> > "[" is a function, and you want to use it on each element of the list, > > so... > > > lapply(x, "[", c(1:7)) > > and the call to c() is of course not necessary, since ":" will generate a vector. > > ______________________________________________ > R-h... at r-project.org mailing listhttps://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guidehttp://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. > > -- > You received this message because you are subscribed to the Google Groups "R-help-archive" group. > To post to this group, send email to r-help-archive at googlegroups.com. > To unsubscribe from this group, send email to r-help-archive+unsubscribe at googlegroups.com. > For more options, visit this group athttp://groups.google.com/group/r-help-archive?hl=en.