Hi all,
I have (yet another) question about a function in R. What I would like to do is test for the presence of a certain value in a vector, and have the positions that this value is at returned to me.
For example, let's say I have a vector:
x <- c(1,1,2,2,3,3,4,4)
Now I would like a function that would return positions 3 and 4 should I test for the value "2". Or 5 and 6 should I test for "3".
Could someone please tell me how I should do this? The "match" function only returns the first position that a value is found at.
Actually, there are different ways of using match(). I think the following does what you want:
> x <- c(1,1,2,2,3,3,4,4)
> # how you were using it
> match(2, x)
[1] 3
> # switch the arguments around to get a non-NA value for each position of x that matches at least one element of a set
> match(x, 2)
[1] NA NA 1 1 NA NA NA NA
> # see which elements of x are in the set {2}
> which(!is.na(match(x, 2)))
[1] 3 4
> # see which elements of x are in the set {3}
> which(!is.na(match(x, 3)))
[1] 5 6
> # see which elements of x are in the set {2,3}
> which(!is.na(match(x, c(2,3))))
[1] 3 4 5 6
>
The operator %in% provides a more intuitive interface for this usage of match().
Of course I could write my own function that loops through the vector and tests for the presence of each value manually but it seems likely that a function that does this is already present in R. No need to re-invent the wheel :-)
As others have already pointed out, which() together with "==" may be all you need.
Thanks very much, Jonck
______________________________________________ [EMAIL PROTECTED] mailing list https://www.stat.math.ethz.ch/mailman/listinfo/r-help
______________________________________________ [EMAIL PROTECTED] mailing list https://www.stat.math.ethz.ch/mailman/listinfo/r-help