如何在r中转置数据

时间:2016-04-11 15:54:56

标签: r

我读过类似的标题,遗憾的是找不到答案。问题是我有以下数据:

            [,1]            [,2]         [,3]       [,4]   [,5]         
HomeTeam "Arsenal"        "Leicester" "Man United" "QPR"  "Stoke"      
AwayTeam "Crystal Palace" "Everton"   "Swansea"    "Hull" "Aston Villa"

我希望它如下:

                   Teams       Opponent 
HomeTeam         Arsenal Crystal Palace  
AwayTeam  Crystal Palace        Arsenal   
HomeTeam1      Leicester        Everton   
AwayTeam1        Everton      Leicester   
HomeTeam2     Man United        Swansea     
AwayTeam2        Swansea     Man United 

我已经尝试了以下命令,但它不正确,只是为了让您知道我想要做什么:

odd <- seq(1, 759, by = 2)
even <- seq(2, 270, by = 2)
df <- data.frame(team = df_1[odd,1], 
                  opponent = df_1[even,1])

问题是:如何修改上面的命令?或者你可以建议我任何其他代码。提前谢谢!

1 个答案:

答案 0 :(得分:1)

说你有这个:

m <- structure(c("Arsenal", "Crystal Palace", "Leicester", "Everton", 
"Man United", "Swansea", "QPR", "Hull", "Stoke", "Aston Villa"
), .Dim = c(2L, 5L), .Dimnames = list(c("HomeTeam", "AwayTeam"
), NULL))

您可以通过以下方式获得结果:

res<-cbind.data.frame(Teams=c(m),Opponent=c(m[2:1,]))
rownames(res)<-make.unique(rep(c("HomeTeam","AwayTeam"),ncol(m)),sep="")
#                   Teams       Opponent
#HomeTeam         Arsenal Crystal Palace
#AwayTeam  Crystal Palace        Arsenal
#HomeTeam1      Leicester        Everton
#AwayTeam1        Everton      Leicester
#HomeTeam2     Man United        Swansea
#AwayTeam2        Swansea     Man United
#....