CptNemo
CptNemo

Reputation: 6755

How do you match each value of a vector with a key-value dictionary?

I have a vector of names (vector_name) and one dataframe (df_dictionary) with two variable: the name-key and the gender-value.

I need to match each value of vector_name with the df_dictionary so to get a corresponding vector_gender.

Upvotes: 0

Views: 2074

Answers (2)

Tyler Rinker
Tyler Rinker

Reputation: 109874

Stealing Simon's data:

##  Dictionary
df <- data.frame( Name = c("John" , "Mary" , "Steve" , "Jordan" , "Bob" , "Alex"),
    Gender = c( "M" , "F" , "M" , "F" , "F" , "F" ) )

## Names to match on
vnames <- c( "John" , "Jordan" , "Kingsley" )

##  Get gender - note: no match for Kingsley so NA returned 
library(qdap)
lookup(vnames, df)

## > lookup(vnames, df)
## [1] "M" "F" NA


## or
vnames %l% df  

## > vnames %l% df  
## [1] "M" "F" NA 

Upvotes: 0

Simon O&#39;Hanlon
Simon O&#39;Hanlon

Reputation: 59970

How about match?

#  Dictionary
df <- data.frame( Name = c("John" , "Mary" , "Steve" , "Jordan" , "Bob" , "Alex"),
                  Gender = c( "M" , "F" , "M" , "F" , "F" , "F" ) )
#        Name Gender
#1   John      M
#2   Mary      F
#3  Steve      M
#4 Jordan      F
#5    Bob      F
#6   Alex      F

# Names to match on
vnames <- c( "John" , "Jordan" , "Kingsley" )

#  Get gender - note: no match for Kingsley so NA returned    
df$Gender[ match( vnames , df$Name ) ]
#[1] M    F    <NA>
#Levels: F M

Upvotes: 2

Related Questions