[R] Indexing a vector by a list of vectors

Erik Iverson iverson at biostat.wisc.edu
Tue Apr 4 23:20:23 CEST 2006


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




More information about the R-help mailing list