如何将矢量的每个值与键值字典相匹配?

时间:2013-08-27 10:59:24

标签: r match

我有一个名称向量(vector_name)和一个带有两个变量的数据帧(df_dictionary):name-key和gender-value。

我需要将vector_name的每个值与df_dictionary匹配,以获得相应的vector_gender。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

窃取西蒙的数据:

##  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