我有一份2009-2017年足球队和他们的输赢结果的数据集。目前的得失都在同一栏中,一个接一个,我想为亏损创建一个新的栏目。
数据的示例如下:
Football <- data.frame (
Season = rep ("2009", 10),
Team = rep (c("ARI", "ARI", "ATL", "ATL", "BAL", "BAL", "BUF", "BUF", "CAR", "CAR")),
Value = c(10, 6, 7, 9, 7, 9, 6, 10, 8, 8)
)我希望最后的产出能显示:
Season Team Wins Losses
2009 ARI 10 6
2009 ATL 7 9
2009 BAL 7 9诸若此类。还有其他几个变量,但是每个赛季/球队的唯一变化就是“价值”。
我已经尝试过几次spread()和mutate()的迭代,但是它们通常比我想要的要多很多列(即2009年want,2009.Losses,2010 want,2010.Losses)。
谢谢你的帮助。我希望这篇文章没问题,这是我第一次发帖。
干杯,杰里米
发布于 2018-04-12 17:09:57
我们创建了一个"Winloss“列,然后将spread设置为”wide“格式
library(tidyverse)
Football %>%
mutate(Winloss = rep(c("Win", "Loss"), n()/2)) %>%
spread(Winloss, Value)
# Season Team Loss Win
#1 2009 ARI 6 10
#2 2009 ATL 9 7
#3 2009 BAL 9 7
#4 2009 BUF 10 6
#5 2009 CAR 8 8数据
Football <- data.frame (
Season = rep ("2009", 10),
Team = rep (c("ARI", "ARI", "ATL", "ATL", "BAL", "BAL", "BUF", "BUF", "CAR", "CAR")),
Value = c(10, 6, 7, 9, 7, 9, 6, 10, 8, 8)
)发布于 2018-04-12 17:26:05
使用reshape2软件包
> Football$WL <- rep(c("Win", "Losses"), nrow(Football)/2)
>
> library(reshape2)
> dcast(Football, Season + Team ~ WL, value.var="Value")
Season Team Losses Win
1 2009 ARI 6 10
2 2009 ATL 9 7
3 2009 BAL 9 7
4 2009 BUF 10 6
5 2009 CAR 8 8https://stackoverflow.com/questions/49802319
复制相似问题