[R] Indexing a vector by a list of vectors

Gabor Grothendieck ggrothendieck at gmail.com
Tue Apr 4 23:52:15 CEST 2006


The following is quite simple although it does use a function:

   lapply(ind, function(x) vec[x])

and if you really don't want to use a function then try:

   mapply("[", rep(list(vec), length(ind)), ind)


On 4/4/06, Erik Iverson <iverson at biostat.wisc.edu> wrote:
> Hello R-help -
>
> I have
>
> vec <- c("string1", "string2", "string3")
> ind <- list(c(1,2),c(1,2,3))
>
> I want "vec" indexed by each vector in the list "ind".
> The first element of the list I want would be vec[c(1,2)],
> the second element would be vec[c(1,2,3)], like the following.
>
> [[1]]
> [1] "string1" "string2"
>
> [[2]]
> [1] "string1" "string2" "string3"
>
> Using for loops, this is simple.  For fun, I tried to implement it
> without a for loop using some combination of *apply() functions and "[".
>
> I succeeded with
>
> myfunc <- function(x) {
>   do.call("[",list(vec,x))
> }
> lapply(ind,myfunc)
>
> I was not, however, able to get my desired result without defining my
> own dummy function.  Can anyone think of a way?  As I said, I already
> have a way that works, I'm just curious if there is a more 'elegant'
> solution that does not rely on my having to define another function.
> Seems like it should be possible.
>
> Thanks, Erik Iverson
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list