[R] perfectionism
jim holtman
jholtman at gmail.com
Fri Nov 25 20:39:46 CET 2011
Try this:
> z <- c(1, 2, 3, 2)
> names(z) <- c("a","b","c","b")
> f <- c("b","c")
> match(f, names(z))
[1] 2 3
> # if you want the names
> x <- match(f, names(z))
> names(x) <- f
> x
b c
2 3
On Fri, Nov 25, 2011 at 2:23 PM, Jack Tanner <ihok at hotmail.com> wrote:
> I have a named vector:
>
>> z <- c(1, 2, 3, 2)
>> names(z) <- c("a","b","c","b")
>> f <- c("b","c")
>
> I want to know the index in z of the first occurrence of each of the values in f.
>
> One implementation is
>
>> sapply(f, function(x) which(names(z)==x)[1])
> b c
> 2 3
>
> Is which() smart enough to stop when it finds in z the first occurrence of every
> value from f, or does it search through all the values in z only to report the
> first one?
>
> Are some more elegant ways of writing this code?
>
> Just curious.
>
> ______________________________________________
> 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
Data Munger Guru
What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.
More information about the R-help
mailing list