2017-02-01 2 views
1

私が2つのデータテーブルを持っている例を考えてみましょう。df1は私の注文のコピーであり、SOHは私のインベントントです。私はそれによって、SOHdf1$priceをマージしたい:与えられたルールで2つのテーブルをマージする

SOH$arrival_year > df1$yearも何ら古い年はSOH項目がdf1に表示されdoesntの場合はNA

を書き表示されない場合は、NAを書き、最も古い年に関連付けられた価格を書きます価格に

supplier <- c(1,1,1,1,1,2,2) 
item <- c(20,20,20,21,22,23,26) 
year <- c(2000,2002,2008,2001,2007,2005,2009) 
price <- c(.3,.4,.5,1.6,1.5,3.2,.25) 
df1 <- data.frame(supplier, item, year, price) 
# 
supplier_on_hand <- c(1,1,1,1,1,1,2,2,3) 
item_on_hand <- c(20,20,20,22,20,20,23,23,10) 
arrival_year <- c(2000,2001,2002,2009,2007,2012,2006,2004,2009) 
SOH <- data.frame(supplier_on_hand, item_on_hand, arrival_year) 

次の出力が要求される:

enter image description here

+0

おそらく 'merge(df1、df2、by.x = c(" Supplier "、" Year ")、by.y = c(" Supplier "、" arrival_year "))'です。 – lmo

答えて

1

次ルックス、それは私の作品のように:

cbind(SOH, price = 
    apply(SOH, 1, function(x) { 
    #setting the item and year constraints 
    temp <- df1[df1$item == x[2] & df1$year <= x[3], ] 
    #order per year descending as per rules 
    temp <- temp[order(temp$year, decreasing = TRUE), ] 
    #set to NA if item or year does not confirm rules 
    if (is.na(temp[1, 'price'])) return(NA) else return(temp[1, 'price']) 
    }) 
) 

出力リレー:

supplier_on_hand item_on_hand arrival_year price 
1    1   20   2000 0.3 
2    1   20   2001 0.3 
3    1   20   2002 0.4 
4    1   22   2009 1.5 
5    1   20   2007 0.4 
6    1   20   2012 0.5 
7    2   23   2006 3.2 
8    2   23   2004 NA 
9    3   10   2009 NA 
2

別の可能性は、ローリングを使用しているがdata.table -packageの能力に参加:

library(data.table) 
setDT(df1)[setDT(SOH), on = .(supplier = supplier_on_hand, item = item_on_hand, year = arrival_year), roll = Inf] 

# in a bit more readable format: 
setDT(SOH) 
setDT(df1) 
df1[SOH, on = .(supplier = supplier_on_hand, item = item_on_hand, year = arrival_year), roll = Inf] 

# or with setting keys first: 
setDT(SOH, key = c('supplier_on_hand','item_on_hand','arrival_year')) 
setDT(df1, key = c('supplier','item','year')) 
df1[SOH, roll = Inf] 

与える:

supplier item year price 
1:  1 20 2000 0.3 
2:  1 20 2001 0.3 
3:  1 20 2002 0.4 
4:  1 20 2007 0.4 
5:  1 20 2012 0.5 
6:  1 22 2009 1.5 
7:  2 23 2004 NA 
8:  2 23 2006 3.2 
9:  3 10 2009 NA 
+0

私は古いバージョンのdata.tableを持っているかどうか分かりませんが、 "関数が見つかりませんでした"というエラーが表示されます。 " – user08041991

+1

@ user08041991おそらく更新が必要です。上記のコードは、最新バージョンの* v1.10.0 *で動作します。 – Jaap

+2

'data.table'にすべてがあることを知っていると思うと、何か新しいポップアップがあります!非常に良いもの。 – LyzandeR

関連する問題