[R] Using Match in a lookup table

David Winsemius dwinsemius at comcast.net
Tue Jun 28 15:39:36 CEST 2011


On Jun 28, 2011, at 6:18 AM, Michael Pearmain wrote:

> Hi All,
>
> I'm having a few problems using match and a lookup table, previous  
> Googling
> show numerous solutions to matching a lookup table to a dataset,
> My situation is slightly different as i have multiple lookup tables,  
> (that i
> cannot merge - for integrity reasons) that i wish to match against  
> my data,
> and each of these files is large, so lots of for / if conditions are  
> not
> ideal. (withstanding that i have multiple files of course)
>
>
> For example,
> I have data:
>
>> v <- c("foo", "foo", "bar", "bar", "baz")
>> id <- c(1,2)
>> id2 <- c(3)
>> name <- c("foo", "bar")
>> name2 <- c("baz")
>> df1 <- data.frame(id, name)
>> df2 <- data.frame(id2, name2)
>
>> v <- df1$id[match(v,df1$name)]
>> v
> [1]  1  1  2  2 NA

A numeric vector.
>
> So here i actually want to return
>> v
> [1]  1  1  2  2 "baz"

Not possibly a numeric vector.

>
> so next time i can run
> v <- df2$id[match(v,df2$name)]
>
> and return:
>> v
> [1]  1  1  2  2 3

You need to keep track of the successful matches in df1 and then ypu  
probably want to interleave them with matches in df2. Perhaps instead  
use ifelse to do the work for you:

 > ifelse(!is.na(match(v,df1$name)), match(v,df1$name),  
match(v,df2$name2) )
[1] 1 1 2 2 1


>
> Any help very much appreciated
>
> Mike
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list