R:匹配2个矩阵的字符串行

时间:2013-06-19 20:30:58

标签: r

我正在使用IP地址数据,我将数据读入字符串。为简单起见,我想出了一个简单的例子。我试图将矩阵“m”的字符串行与矩阵“abc”中的字符串匹配。但我一直未能得到正确的输出。

> 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"

我得到输出,这没有任何意义:

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

我期待输出 [1] 1 NA 2 NA NA

1 个答案:

答案 0 :(得分:3)

这是一个factor问题,请尝试这样做:

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