描述

    通过增加列数和减少行数,将data_frame从长格式转换为宽格式。

    长表变宽表 - 图1

    1. stocks = data.frame(
    2. time = as.Date('2009-01-01') + 0:9,
    3. X = rnorm(10, 0, 1),
    4. Y = rnorm(10, 0, 2),
    5. Z = rnorm(10, 0, 4)
    6. ) %>%
    7. longer_dt(time) -> longer_stocks
    8. longer_stocks
    9. longer_stocks %>%
    10. wider_dt("time",
    11. name = "name",
    12. value = "value")
    13. longer_stocks %>%
    14. mutate_dt(one = 1) %>%
    15. wider_dt("time",
    16. name = "name",
    17. value = "one")
    18. ## using "fun" parameter for aggregation
    19. DT <- data.table(v1 = rep(1:2, each = 6),
    20. v2 = rep(rep(1:3, 2), each = 2),
    21. v3 = rep(1:2, 6),
    22. v4 = rnorm(6))
    23. ## for each combination of (v1, v2), add up all values of v4
    24. DT %>%
    25. wider_dt(v1,v2,
    26. value = "v4",
    27. name = ".",
    28. fun = sum)