2014-07-04 54 views
0

我有一個數據幀P,它具有因子變量「m」和「q」。另外,具有因子變量「m」,「q」,「f」和「t」的數據幀D。我想獲得與因子「m」個新的數據幀H,「Q」,「F」和「t其中。R:如何將較低維數據幀與較高維數據幀相乘作爲標量

H(m,f,q,t) = P(m,q) * D(m,q,f,t) for all m,q,f and t. 

從本質上講,我要合併的共享變量「米的兩個數據幀「和 'q' 和增加他們Val

的數據被保存在以下格式:

> head(P) 
        m  q Val 
raw1.Prio0  raw1 Prio0 0.5 
raw1.Prio1  raw1 Prio1 0.7 
raw2.Prio0  raw2 Prio0 1 
raw2.Prio1  raw2 Prio1 1 
product.Prio0 product Prio0 0.5 
product.Prio1 product Prio1 1 

> head(D) 
          m  q f t  Val 
product.Prio0.a.P01 product Prio0 a P01 445.6159 
product.Prio0.a.P02 product Prio0 a P02 445.6159 
product.Prio0.a.P03 product Prio0 a P03 445.6159 
product.Prio0.a.P04 product Prio0 a P04 1445.6159 
product.Prio0.a.P05 product Prio0 a P05 1445.6159 
product.Prio0.b.P01 product Prio0 b P01 176.0000 

的結果應該是這樣的:

> head(H) 
          m  q f t  Val 
product.Prio0.a.P01 product Prio0 a P01 222.808 
product.Prio0.a.P02 product Prio0 a P02 222.808 
product.Prio0.a.P03 product Prio0 a P03 222.808 
product.Prio0.a.P04 product Prio0 a P04 722.808 
product.Prio0.a.P05 product Prio0 a P05 722.808 
product.Prio0.b.P01 product Prio0 b P01 88.000 

回答

0

試試這個:

H<-merge(P,D, by=c("m","q")) 

H$Val <- H$Val.x * H$Val.y 

它輸出:

> H 
     m  q Val.x f t  Val.y  Val 
1 product Prio0 0.5 a P01 445.6159 222.808 
2 product Prio0 0.5 a P02 445.6159 222.808 
3 product Prio0 0.5 a P03 445.6159 222.808 
4 product Prio0 0.5 a P04 1445.6159 722.808 
5 product Prio0 0.5 a P05 1445.6159 722.808 
6 product Prio0 0.5 b P01 176.0000 88.000 
+0

THX,這正是我需要的。 – MarvMind