[R] How to match vector with a list ?

Linlin Yan yanlinlin82 at gmail.com
Mon Mar 8 12:22:37 CET 2010


Maybe you can create a helper vector first:
> helper <- structure(names = unlist(j), rep(names(j), sapply(j, length)))
> helper
   a    c    b    d
"j1" "j1" "j2" "j2"
> helper[i]
   a    a    b    b    b    c    c    d
"j1" "j1" "j2" "j2" "j2" "j1" "j1" "j2"

On Sat, Mar 6, 2010 at 1:42 AM, Carlos Petti <carlos.petti at gmail.com> wrote:
> Dear list,
>
> I have a vector of characters and a list of two named elements :
>
> i <- c("a","a","b","b","b","c","c","d")
>
> j <- list(j1 = c("a","c"), j2 = c("b","d"))
>
> I'm looking for a fast way to obtain a vector with names, as follows :
>
> [1] "j1" "j1" "j2" "j2" "j2" "j1" "j1" "j2"
>
> I used :
>
> match <- lapply(j, function (x) {which(i %in% x)})
> k <- vector()
> for (y  in 1:length(match)) {
> k[match[[y]]] <- names(match[y])}
> k
> [1] "j1" "j1" "j2" "j2" "j2" "j1" "j1" "j2"
>
> But, I think a better way exists ...
>
> Thanks in advance,
> Carlos
>
>        [[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