[R] How to match vector with a list ?
jim holtman
jholtman at gmail.com
Fri Mar 5 19:25:21 CET 2010
try this:
> i <- c("a","a","b","b","b","c","c","d")
>
> j <- list(j1 = c("a","c"), j2 = c("b","d"))
>
> # create a matrix for mapping
> map <- do.call(rbind, lapply(names(j), function(x) cbind(x, j[[x]])))
> # generate your output
> map[match(i, map[,2]),1]
[1] "j1" "j1" "j2" "j2" "j2" "j1" "j1" "j2"
>
On Fri, Mar 5, 2010 at 12:42 PM, 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.
>
--
Jim Holtman
Cincinnati, OH
+1 513 646 9390
What is the problem that you are trying to solve?
More information about the R-help
mailing list