logo

Comparing the Elements of Two Arrays in R 📂R

Comparing the Elements of Two Arrays in R

Overview

R is widely used in fields that care more about the content of data than its form or structure, so comparing data is likewise useful.

Inclusion Relation

20190109\_120126.png (This is not important at all, but in the example A denotes the triangular numbers $\displaystyle {{n(n+1)} \over {2}}$ and B denotes the square numbers $m^2$.)

Using the binary operator %in% to compare two arrays returns true for the elements of A that also belong to B, and false otherwise. By applying the strsplit() function that splits strings and its applications as follows, it can also be used to search for letters or words.

20190109\_124542.png

Intersection and Symmetric Difference

20190109\_124805.png

The intersect() function and the setdiff() function compute $A \cap B$ and $A \triangle B = ( A \cup B ) \setminus ( A \cap B )$, respectively. (Likewise, this is not important at all, but one can see that $1$ and $36$ are both triangular and square numbers.)

Code

A<-((1:14)*(2:15))/2; A
B<-(1:10)^2; B
 
A %in% B
 
c("은") %in% strsplit("달변은 은이요 침묵은 금이다","")[[1]]
 
intersect(A,B)
 
setdiff(A,B)