Quantcast
Channel: Greetz to Geeks
Viewing all articles
Browse latest Browse all 10

Match function in R

$
0
0

The match() function returns a vector of the position of first occurrence of the vector1 in vector2. If the element of the vector1 does not exist in vector2, NA is returned.

Syntax: match(vector1, vector2, nomatch = NA_integer_, incomparables = NULL)

vector1: vector, the values to be matched
vector2: vector, the values to be matched against
nomatch: the value which should be returned when no match is found
incomparables: the vector of values that cannot be matched.

By default the nomatch argument will return NA in case the match is not found in vector2.

According to the R Documentation  the %in% operator is equivalent to match(). It is a logical vector which indicates whether a match was located for vector1 in vector2. The result value will be either TRUE or FALSE but never NA. So the %in% operator can be useful in if conditions.

Syntax: vector1 %in% vector2

Examples:

print(match(5, c(1,2,9,5,3,6,7,4,5)))
[1] 4
5 %in% c(1,2,9,5,3,6,7,4,5)
[1] TRUE
8 %in% c(1,2,9,5,3,6,7,4,5)
[1] FALSE
> v1 <- c("a1","b2","c1","d2")
> v2 <- c("g1","x2","d2","e2","f1","a1","c2","b2","a2")
> x <- match(v1,v2)
> x
[1] 6 8 NA 3
> v1 <- c("a1","b2","c1","d2")
> v2 <- c("g1","x2","d2","e2","f1","a1","c2","b2","a2")
> v1 %in% v2
[1] TRUE TRUE FALSE TRUE
> v1 <- c("a1","b2","c1","d2")
> v2 <- c("g1","x2","d2","e2","f1","a1","c2","b2","a2")
> x <- match(v1,v2, nomatch = 0)
> x
[1] 6 8 0 3
> v1 <- c("a1","b2","c1","d2")
> v2 <- c("g1","x2","d2","e2","f1","a1","c2","b2","a2")
> x <- match(v1,v2, nomatch = 0, incomparables = "a1")
> x
[1] 0 8 0 3

 

 

 

 

 

 

 

 

 

 

 


Viewing all articles
Browse latest Browse all 10

Trending Articles