0

I have a 1 column matrix with labels and a numeric vector.
I want to extract the labels in the matrix which are equal to one of the entries in that vector, more specifically:

> mat
                 [,1]
intercept 20.86636535  
crim      -0.23802478  
zn         0.03822050  
indus      0.05135584  
chas       2.43504780

> vec  
[1] -0.23802478  0.05135584

> mat[2, 1] == vec[1]
crim 
FALSE 

Currently I'm stuck with the first step. I have no idea why it returns FALSE while they hold the same numeric values.

RiskyMaor
  • 308
  • 2
  • 15
  • Try `mat %in% vec` or such. See also [this](https://stackoverflow.com/questions/1169248/r-function-for-testing-if-a-vector-contains-a-given-element) – David Arenburg Jun 13 '17 at 07:27
  • I get a vector in length 5 which all entries are FALSE. – RiskyMaor Jun 13 '17 at 07:29
  • 1
    Then you have a [floating points](https://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal) problem. Compare `print(mat, digits = 20)` vs `print(vec, digits = 20)` – David Arenburg Jun 13 '17 at 07:30

1 Answers1

0

I'd use round(as.numeric(mat[,2, drop=T]), 5) %in% round(vec, 5) , as there may well be floating point issues.

Doing so yields:

[1] FALSE TRUE FALSE TRUE FALSE

Basically, you need to turn the second column into a vector (using drop=T) and then turn it from a character to a numeric. The rounding (in this case, to 5 decimal places) then bridges the floating point problem that I mentioned before (along with David Arenburg).

I hope that helps you.

p0bs
  • 1,004
  • 2
  • 15
  • 22