在 r 中将 1 列的数据分成 2 列
Separate data from 1 column into 2 in r
我有一个足球队数据集及其 Win/Loss 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
等等。还有其他几个变量,但每个 Season/Team 对唯一变化的是 "Value".
我已经尝试了 spread() 和 mutate() 的几次迭代,但它们通常会生成更多列(即 2009.Wins、2009.Losses、2010.Wins、2010.Losses ) 比我想要的。
感谢您的帮助。我希望这 post 结果没问题,这是我第一次 posting。
干杯,杰里米
我们创建一列"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)
)
使用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
我有一个足球队数据集及其 Win/Loss 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
等等。还有其他几个变量,但每个 Season/Team 对唯一变化的是 "Value".
我已经尝试了 spread() 和 mutate() 的几次迭代,但它们通常会生成更多列(即 2009.Wins、2009.Losses、2010.Wins、2010.Losses ) 比我想要的。
感谢您的帮助。我希望这 post 结果没问题,这是我第一次 posting。
干杯,杰里米
我们创建一列"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)
)
使用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