Hi, I am trying to a function in R and I am pretty new to this. I have a matrix like this ( this is the code for the matrix): k2=c(3,6,4,NA,NA,NA,NA) k3=c(2,7,5,NA,NA,NA,NA) k4=c(7,9,5,2,1,8,12) df2=data.frame(k2,k3,k4) m2=as.matrix(df2) m2 The main idea to find a value in the k4 row. If the value is not the same for that row, the function should check the values in the same row, and go to these rows instead to find the value.So if the value is less than val in [1,k4] then it should take the second column value in the same row ([1,k3])as the row number to go for and check the value in the third column in that row [value of row,3]. If the value is the greater, itshould do same thing as before, but with [1,k2]. And if the value is again not the needed one it should again check and repeat the same procedure for that next row until it gets the match. Example : So if I need val=5 then it should check if it is the same value as [1,k4] which is 7 and it is not, it should then go to third low check [3,k4] and as you can see it is the same, which means it is going to print 5. If I need the value I need is 12, then if should the logic be like this : the val is not the same as 7, so go to the third row, check with 9, oh its not the same value, the I will go to the 7 row, and there it is, its same val, I will print then... **My code so far/My progress** I know that I have to search the third every column time, so that means, beginning with the first for (i in df2[1,3]) And then check if each value in that column is not equal to val: if (!i == val) And here comes the tricky part for me. I understand that I have to make a check if its less or greater, which means that is should somehow be like this if (!i == val) #then check if its less, if yes, go that row #if it greater then go then go that row # go to that row and check the same thing there And I do not know how to do that, so that it repeats itself for every row until it finds the value in val. I know that I can assing the row for smaller value as n-2 and the row for the bigger value as n-1, but I am strugling here to make it work. As I said, I have very little experience in programming so any help would be appreciated.