MATCH function in r [duplicate]

First you have typos in your example. Secondly, the assignment of ‘list1$test1value’ should have an ‘[i]’ added to it to not save over each round. There should also not be an ‘[i]’ added to list2$id since you want to search the entire vector for the lookup.

for (i in 1:length(list1)) { 
  list1$test1value[i] <- list2$test[match(list1$id[i], list2$id,
                             nomatch = NA_integer_, incomparables = NULL)] }

The code works, but there is no reason for any loops here. You are showing a lack of understanding in how R operates. The below code does the exact same thing much faster.

list1$test1value <- list2$test[match(list1$id, list2$id)]

R is built so that you do not have to hold its hand and instruct it how to go through each element of the vector. match will automatically iterate through each member one by one and look it up in the other vector for you. It will also assign the result in an orderly way in the dataset.

I will close this as a duplicate because as others suggested, merge is perfect for this.

merge(list1, list2[c("id", "test")], all.x=TRUE)
#  id age  name test
#1  1  40 danny  100
#2  2  16  nora   NA
#3  3  35 james   NA
#4  4  21   ben   55

Leave a Comment