find a similar element between two data

advertisements

I asked a question before which was complicated and I did not get any help. So I tried to simplify the question and input output.

I have tried many ways but none worked for example , I sort down some

# 1

for(i in ncol(mydata)){
    corsA  = grep(colnames(mydata)[i] , colnames(mysecond))
    mydata[,corsA]%in%mysecond[,i]}
# here if I get true then means they have match

## 2

are.cols.identical <- function(col1, col2) identical(mydata[,col1], mysecond[,col2])
res <- outer(colnames(mydata), colnames(mysecond),FUN = Vectorize(are.cols.identical))
cut <- apply(res, 1, function(x)match(TRUE, x))

### 3

(mydata$Rad) %in% (mysecond$Ro5_P1_A5)

#### 4

which(mydata %in% mysecond)

#### 5

match(mydata$sus., mysecond$R5_P1_A5)

or

which(mydata$sus. %in% mysecond$RP1_A5)

matches <- sapply(mydata,function(x) sapply(mysecond,identical,x))

and few others, but none led me to an answer


Here is another solution using regex:

rows<-mapply(grep,mysecond,mydata)

The step above will return a list with the matched rows in each column:

rows

If you would like to see how many rows where matched you can do this:

lapply(rows,length)

Now we can go ahead a get the rows of interest in mydata, but rows is a list so we need to unlist() and we might have some duplicate rows, and we don't want them to appear twice in the output, so we use the unique() function:

rows<-unique(unlist(rows))
mydata[rows,]
#View(mydata[rows,])