[R] Help: extrac the first entry for each component of a list

Gustavo Carvalho gustavo.bio+R at gmail.com
Wed Aug 24 05:26:47 CEST 2011


sapply(a, `[`, 1)

On Wed, Aug 24, 2011 at 12:18 AM, Chee Chen <chee.chen at yahoo.com> wrote:
> Dear All,
> I would like to know, beside writing a function and then apply it to a list, or using a for loop, whether there is a one-line command to do the following.
> Suppose we have a list, each of whose components are numeric:
>> a <- vector("list",3)
>> a[[1]] <-c(1,2)
>> a[[2]] <-c(3,4)
>> a[[3]] <- c(5,6)
>> a
> [[1]]
> [1] 1 2
>
> [[2]]
> [1] 3 4
>
> [[3]]
> [1] 5 6
>
> Target: I would like to extract from each of its components the first entry and store them into a vector, ie, to extract 1 from a[[1]], 3 from a[[2]], 5 from a[[3]], and store 1,3,5 into a vector without using for loops.
> Thank you,
> Chee
>        [[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.
>



More information about the R-help mailing list