mynameisJEFF
mynameisJEFF

Reputation: 4239

R: matching rows of strings of 2 matrices

I am working with IP address data and I read in the data as strings. For simplicity, I conjure up an easy example. I tried to match the rows of strings of matrix "m" to those in matrix "abc". But I kept failing to get correct output.

> abc <- matrix(c("dog", "king", "bee", "cat", "apple","eel", "crab", "ball","soap","crazy"), nrow = 5)
> abc
     [,1]    [,2]   
[1,] "dog"   "eel"  
[2,] "king"  "crab" 
[3,] "bee"   "ball" 
[4,] "cat"   "soap" 
[5,] "apple" "crazy"

> m <- matrix(c("dog", "bee","eel","ball" ), nrow = 2)
> m
     [,1]  [,2]  
[1,] "dog" "eel" 
[2,] "bee" "ball"

I get output, which doesnt make any sense:

> match(data.frame(t(abc)), data.frame(t(m)))
[1] 1 2 2 1 1

I am expecting output to be [1] 1 NA 2 NA NA

Upvotes: 2

Views: 170

Answers (1)

eddi
eddi

Reputation: 49448

It's a factor issue, try this instead:

match(data.frame(t(abc), stringsAsFactors = F),
      data.frame(t(m), stringsAsFactors = F))
#[1]  1 NA  2 NA NA

Upvotes: 3

Related Questions