【问题标题】:Separate data from 1 column into 2 in r将数据从 1 列分成 r 中的 2
【发布时间】:2018-04-12 17:06:37
【问题描述】:

我有一个包含 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.Wins、2009.Losses、2010.Wins、2010.Losses)。

感谢您的帮助。我希望这篇文章能顺利,这是我第一次发帖。

干杯,杰里米

【问题讨论】:

  • 所以格式不是很好,但所需输出中的每个“2009”都应该是新行的开始
  • 赢与输从何而来?您可以使用 aggregate() 来完成此操作。

标签: r spread


【解决方案1】:

我们创建一列“Winloss”,然后将spread 转换为“宽”格式

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

【讨论】:

  • Football %&gt;% group_by(Team) %&gt;% mutate(Winloss = c("Win", "Loss")) %&gt;% spread(Winloss, Value)。如果任何团队有 nrows != 2,这有利于产生警告
  • 非常感谢 akrun 和 Renu,尤其是回复如此迅速!
【解决方案2】:

使用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   8

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-21
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多