Crosschecking numbers of a matrix in R

Viewed 41

I'm currently working with a large matrix of two columns, and what I want to check is If every line/combination (two columns) is also present in a dataframe loaded (two columns as well).

Example,

(obj_design <- matrix(c(2,5,4,7,6,6,20,12,4,0), nrow = 5, ncol = 2))
     [,1] [,2]
[1,]    2    6
[2,]    5   20
[3,]    4   12
[4,]    7    4
[5,]    6    0

(refined_grid <- data.frame(i=1:4, j=1:12))
   i  j
1  1  1
2  2  2
3  3  3
4  4  4
5  1  5
6  2  6
7  3  7
8  4  8
9  1  9
10 2 10
11 3 11
12 4 12

Following the reproducible example, it would be selected (2,6) and (4,12).

I'm wondering if there's a function that I can use to check the whole matrix, and see if a specific line is in the dataframe, and (if possible) write separately (new dataset) which elements of the matrix it is in.

Any assistance would be wonderful.

2 Answers

This code will give you which rows of the matrix exist in the dataframe.

which(paste(obj_design[,1], obj_design[,2]) %in%
      paste(refined_grid$i, refined_grid$j)
)

Then you can just assign it to a vector!

Here is an option with match

i1 <-  match(do.call(paste, as.data.frame(obj_design)),
            do.call(paste, refined_grid), nomatch = 0)
refined_grid[i1,]
Related