Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 尝试从长格式转换为宽格式,但最终会出现变量的每个组合_R_Tidyr - Fatal编程技术网

R 尝试从长格式转换为宽格式,但最终会出现变量的每个组合

R 尝试从长格式转换为宽格式,但最终会出现变量的每个组合,r,tidyr,R,Tidyr,我想从这个结构出发: 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 =

我想从这个结构出发:

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")

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

1。数据表

我们可以使用
data.table
的devel版本中的
dcast
,即
v1.9.5
,它可以采用多个“value.var”列。它可以从安装

将“data.frame”转换为“data.table”(
setDT(d)
),创建一个按“game_id”分组的序列列(“ind”),然后在修改后的数据集上使用
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”列后使用
base R
中的
restrape

 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

d11。数据表

我们可以使用
data.table
的devel版本中的
dcast
,即
v1.9.5
,它可以采用多个“value.var”列。它可以从安装

将“data.frame”转换为“data.table”(
setDT(d)
),创建一个按“game_id”分组的序列列(“ind”),然后在修改后的数据集上使用
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”列后使用
base R
中的
restrape

 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

d1@tcash21没问题。我认为
spread
(目前)只能使用单值列(尚未检查新的渐晕图)。@tcash21没问题。我认为
spread
(目前)只能采用单值列(尚未检查新的渐晕图)。