-1

我已经搜索了档案,但对这个问题无济于事我涉及到 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,]

我在合并时也遇到了问题,因为雷吉杰克逊有 2 个不同的合同年,它正试图合并两者。

对此的任何帮助或建议将不胜感激。

4

1 回答 1

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
于 2013-10-19T16:45:16.540 回答