1

我想从这个结构中走出来:

game_id team pts
1 400597848 TOWS  53
2 400597848 COFC  50
3 400595519  ILL  49
4 400595519  WIS  68

对此:

game_id team1 pts1 team2 pts2
1 400597848 TOWS  53  COFC  50
3 400595519  ILL  49  WIS  68

这是示例数据:

d <- structure(list(game_id = c(400597848L, 400597848L, 400595519L,
400595519L), team = c("TOWS", "COFC", "ILL", "WIS"), pts = c(53L,
50L, 49L, 68L)), .Names = c("game_id", "team", "pts"), row.names = c(NA,
4L), class = "data.frame")

我已经尝试使用tidyr并遵循本教程: http: //www.cookbook-r.com/Manipulating_data/Converting_data_between_wide_and_long_format/

但是,当我尝试:

 spread(d, team, pts)

我得到所有团队的重复列,但不想要所有组合。

4

1 回答 1

4

1. 数据表

我们可以使用iedcast的开发版本,它可以采用多个 'value.var' 列。它可以从.data.tablev1.9.5here

将“data.frame”转换为“data.table”(setDT(d)),创建一个序列列(“ind”),按“game_id”分组,然后dcast在修改后的数据集上使用,将“value.var”指定为“team” , 和'pts'。

dcast(setDT(d)[, ind:= 1:.N, by=game_id], game_id~ind, 
                   value.var=c('team', 'pts'))
#     game_id 1_team 2_team 1_pts 2_pts
#1: 400595519    ILL    WIS    49    68
#2: 400597848   TOWS   COFC    53    50

2.基础R

另一种选择是在创建“ind”列之后使用reshapefrom 。base R

 d1 <- transform(d, ind=ave(seq_along(game_id), game_id, FUN=seq_along))

 reshape(d1, idvar='game_id', timevar='ind', direction='wide')
 #    game_id team.1 pts.1 team.2 pts.2
 #1 400597848   TOWS    53   COFC    50
 #3 400595519    ILL    49    WIS    68
于 2015-03-22T16:37:45.803 回答