mrhappysmile
mrhappysmile

Reputation: 91

Exiting loop to early or only taking one of a value if its repeated in R

The following is some syntax relating to the problem I want to solve, but a more simplified version.

Say I want to take all the values from one matrix and find if they exist in a specific column of another matrix then from there add them to an empty list.

So:

mat1 <- c(1,2,3)
mat2 <- matrix(c(1,2,1,2,2,2,4,21,5153,15315,21,2,2,2,2,2,2,2,2314,1,1,1,1,1), nrow =6, ncol =4, byrow = TRUE)

i = 1
j = 1
list_final <- c()
while(i < length(mat1)+1){
    if(mat2[j,2] <- mat1[i]){
        list_final[j] <- mat2[j,2]
        #print(list_final) 
    j=j+1
    }
    i = i+1
}

Following running this, the list list_final is identical to mat1, but I want it to display:

[1] 1 2 3 2 2 1 

What am I doing wrong?

Just as a follow up, is it better practise to sort it during the loop or after?

ie have an additional line after the list has been appended doing the following:

[1] 1 2 3 2 2 1 to [1] 1 1 2 2 2 3

I am also trying to improve my 'elegance' where possible. Is there a way I can make this code more attractive/efficient rather than requiring two loops...

Upvotes: 1

Views: 52

Answers (1)

papgeo
papgeo

Reputation: 473

this command will tell you which values in mat1 are also in the first column of mat2:

mat1[which(mat1 %in% mat2[,1])]

and so with this loop you will go over all columns of mat2

for (i in 1:NCOL(mat2))
    list_final<-c(list_final,mat1[which(mat1 %in% mat2[,i])])

if you want to sort

sort(list_final)

I didn't see any 3's in mat2.

Upvotes: 1

Related Questions