2013-10-19 43 views
-1

我已經通過存檔搜索並且無法解決這個問題我涉及了2個相關數據框的子集,一個數據框是關鍵字,另一個是年度列表,我想用這個鍵來創建一個子集和一個索引。我嘗試過使用子集公式,但是我的代碼沒有適當地符合我的標準。下面是數據:從r中的2個相關數據框中進行子集合併合並

players <- c('Albert Belle','Reggie Jackson', 'Reggie Jackson') 
contract_start_season <- c(1999,1977,1982) 
contract_end_season <- c(2003, 1981, 1985) 
key <- data.frame (player = players, contract_start_season, contract_end_season) 
player_data <- data.frame(season = c(seq(1975,1985),seq(1997,2003)), player = c(rep('Reggie Jackson',times=11),rep('Albert Belle', times=7))) 

我想使用的關鍵子集玩家數據到那些年,所以傑克遜1977年至1981年,然後1982年至1985年和1999年艾伯特百麗2003年我還想創建一個索引,例如雷吉 - 傑克遜1977年將是一年1,1978年2等...

我不合並看起來像這樣嘗試的代碼,它不工作:

player_data[player_data$season >= key$contract_start_season&player_data$season <= key$contract_end_season,] 

合併時我也遇到問題,因爲雷吉傑克遜有兩個不同的合同年,它是試圖合併兩者。

對此的任何幫助或建議將超級讚賞。

回答

1

您是否正在嘗試沿着以下方向行事?

library(data.table) 

key <- data.table(key) 
player_data <- data.table(player_data) 

#Adding another column called season to help in the merge later 
key[,season := contract_start_season] 

# Index on which to merge 
setkeyv(key, c("player","season")) 
setkeyv(player_data, c("player","season")) 

#the roll = Inf makes it like a closest merge, instead of an exact merge 
key[player_data, roll = Inf] 

輸出:

> key[player_data, roll = Inf] 
      player season contract_start_season contract_end_season 
1: Albert Belle 1997     NA     NA 
2: Albert Belle 1998     NA     NA 
3: Albert Belle 1999     1999    2003 
4: Albert Belle 2000     1999    2003 
5: Albert Belle 2001     1999    2003 
6: Albert Belle 2002     1999    2003 
7: Albert Belle 2003     1999    2003 
8: Reggie Jackson 1975     NA     NA 
9: Reggie Jackson 1976     NA     NA 
10: Reggie Jackson 1977     1977    1981 
11: Reggie Jackson 1978     1977    1981 
12: Reggie Jackson 1979     1977    1981 
13: Reggie Jackson 1980     1977    1981 
14: Reggie Jackson 1981     1977    1981 
15: Reggie Jackson 1982     1982    1985 
16: Reggie Jackson 1983     1982    1985 
17: Reggie Jackson 1984     1982    1985 
18: Reggie Jackson 1985     1982    1985 
+0

排序的,但我要排除並非關鍵中的年,所以例如雷吉 - 傑克遜的年會是1977年至1981年,然後1982年至1985年,然後阿爾伯特百麗的將會是1999年到2003年。我可以合併,我只是希望它能夠根據關鍵的設置標準進行子集合。 – abresler

+0

其實只是拿出NA,使我覺得這項工作!讓我試試 – abresler

+0

試試'key [player_data,roll = Inf] [!is.na(contract_start_season)]' – TheComeOnMan