我有一个名称向量(vector_name)和一个带有两个变量的数据框(df_dictionary):名称键和性别值。
我需要将vector_name 的每个值与df_dictionary 相匹配,以便获得相应的vector_gender。
怎么样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
窃取西蒙的数据:
## 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