【发布时间】:2023-04-02 22:38:02
【问题描述】:
我正在使用的数据的一个小样本如下:
structure(list(`Team Code` = c(107, 277, 129, 1320, 27, 694,
231, 306, 314, 465), `Opponent Code` = c(277, 107, 1320, 129,
694, 27, 306, 231, 465, 314), Year = c(2016, 2016, 2016, 2016,
2016, 2016, 2016, 2016, 2016, 2016), Date = structure(c(17040,
17040, 17045, 17045, 17045, 17045, 17045, 17045, 17045, 17045
), class = "Date"), HomeTeam = c(0, 0, 1, 0, 0, 1, 1, 0, 0, 1
), Points = c(51, 31, 49, 3, 13, 20, 13, 34, 13, 63), OppPoints = c(31,
51, 3, 49, 20, 13, 34, 13, 63, 13), Total = c(82, 82, 52, 52,
33, 33, 47, 47, 76, 76), MOV = c(-20, 20, -46, 46, 7, -7, 21,
-21, 50, -50), Spread = c(-22, 22, -32, 32, 22.5, -22.5, 4, -4,
40, -40)), row.names = c(1489L, 1490L, 297L, 298L, 1453L, 1454L,
1915L, 1916L, 2121L, 2122L), class = "data.frame")
我需要创建一个新的数据框,其中包含唯一年份、日期和列名。我已经能够使用以下代码对 Points 和 OppPoints 列执行此操作,但是当我将其扩展到这两列之外时,我会遇到长度错误。所需的输出与下面完全相同,只是希望为 Total、MOV 和 Spread 添加更多行。
我尝试过的代码长度错误:
Data$Stat_Name <- colnames(Data[,6:10])
产生部分预期结果的代码:
Data$Stat_Name <- colnames(Data[,6:10])
部分期望结果:
structure(list(Year = c(2016, 2016, 2016, 2016, 2016, 2016, 2016,
2016), Date = structure(c(17040, 17040, 17045, 17045, 17046,
17046, 17047, 17047), class = "Date"), Stat_Name = c("Points",
"OppPoints", "Points", "OppPoints", "Points", "OppPoints", "Points",
"OppPoints")), row.names = c(1489L, 1490L, 297L, 298L, 355L,
356L, 85L, 86L), class = "data.frame")
【问题讨论】:
-
您可能需要
paste(colnames(Data)[6:10], collapse = "_"),因为长度不等于行数 -
是否有任何你想要实现的逻辑(虽然从帖子中不清楚)
-
嘿@akrun,没有任何逻辑,除了我只需要一个包含年份、日期和列名列的所有唯一组合的数据框。我很快就能测试你上面的代码。您上面的代码是一个非常好的主意。然后我可以使用单独的行并获得所需的结果!谢谢!如果您将提交作为答案,我将接受!