2013-08-27 114 views
0

我有一個向量的名稱(vector_name)和一個數據框(df_dictionary)有兩個變量:名稱鍵和性別值。如何使用鍵值字典匹配矢量的每個值?

我需要將vector_name的每個值與df_dictionary匹配,以獲得相應的vector_gender。

+2

一個小例子將是一件好事。也許一些樣本輸入和所需的輸出。 –

回答

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 
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 
相關問題