I have the following data.frame
df = structure(list(HEADER = c("HOME_TRPM", "AWAY_TRPM", "HOME_TEAM","AWAY_TEAM"),
price = c("0.863104076023855", "-0.845186446996287","CHA", "NOP")),
.Names = c("HEADER", "price"), row.names = c(NA, 4L), class = "data.frame")
df
#> HEADER price
#> 1 HOME_TRPM 0.863104076023855
#> 2 AWAY_TRPM -0.845186446996287
#> 3 HOME_TEAM CHA
#> 4 AWAY_TEAM NOP
我希望你能够帮我转置数据。我该如何在dplyr中实现而不使用t()函数?我尝试过。
df %>% tidyr::spread(HEADER , price)
但它不会提供一个扁平的结构,而是做了这个操作:
structure(list(AWAY_TEAM = c(NA, NA, NA, "NOP"),
AWAY_TRPM = c(NA, "-0.845186446996287", NA, NA),
HOME_TEAM = c(NA, NA, "CHA", NA),
HOME_TRPM = c("0.863104076023855", NA, NA, NA)),
.Names = c("AWAY_TEAM", "AWAY_TRPM", "HOME_TEAM", "HOME_TRPM"),
class = "data.frame", row.names = c(NA, 4L))
生成的数据框应该像这样:
structure(list(HOME_TRPM = "0.863104076023855",
AWAY_TRPM = "-0.845186446996287",
HOME_TEAM = "CHA",
AWAY_TEAM = "NOP"),
.Names = c("HOME_TRPM", "AWAY_TRPM", "HOME_TEAM", "AWAY_TEAM"),
row.names = c(NA, -1L), class = "data.frame"))
do.call(rbind, c(df))
可以在不使用t()
的情况下进行转置。 - Rich ScrivensetNames(do.call(data.frame, as.list(DF[[2]])), DF[[1]])
这样的,但在 dplyr 中几乎不可能实现,因为它并不是围绕数据清洗而设计的。 - Frank