2013-07-31 70 views
0
其他兩個變量的比賽

我有一個看似簡單的問題,我不能回答:我有三個矢量:複製變量R中

x <- c(1,2,3,4) 
weight <- c(5,6,7,8) 
y <- c(1,1,1,2,2,2) 

我想創建一個新的載體該複製權重的值中的每個x中的元素相匹配ý使得其產生其中y相關聯的以下新的權重向量的時間:

y_weight <- c(5,5,5,6,6,6) 

上如何做到這一點(或者循環或向量化)任何想法?謝謝

+1

'重使用[na.omit(比賽(Y,X))]' – Arun

回答

4

你想要match功能。

match(y, x) 

返回匹配的indicies,即建立新的權重向量

weight[match(y, x)] 
0
#Using plyr 

library(plyr) 
df<-as.data.frame(cbind(x,weight)) # converting to dataframe 
df<-rename(df,c(x="y")) # rename x as y for joining dataframes 
y<-as.data.frame(y) # converting to dataframe 
mydata <- join(df, y, by = "y",type="right") 
> mydata 
    y weight 
1 1  5 
2 1  5 
3 1  5 
4 2  6 
5 2  6 
6 2  6