2016-08-16 467 views
1

儘管複雜的標題應用分類,給一個變量,我想做的事情很簡單:試圖在一個數據幀中的另一個數據幀

如果我有兩個dataframes:

d <- data.frame(V1 = c("a","b","c","d"), V2 = c("P", "M", "M", "P")) 
j <- data.frame(V3 = c("d","b","b","c","d","c", "a")) 

和我要插入另一列到數據幀Ĵ,稱爲V4其分配同一分類中的d,即最終的數據框的樣子:

j 

V3 V4 
d P 
b M 
b M 
c M 
d P 
c M 
a P 

回答

0

您可以使用match

j$V4 <- d$V2[match(j$V3, d$V1)] 

j 
# V3 V4 
#1 d P 
#2 b M 
#3 b M 
#4 c M 
#5 d P 
#6 c M 
#7 a P 
+1

太感謝你了! – demsav

0

看起來要執行聯接,或合併歌劇重刑,因爲這樣的:

j <- merge(x=j,y=d,by.x="V3",by.y="V1",sort=FALSE) colnames(j) <- c("V3","V4")