[R] Reorganize the data (dplyr or other packages?)

Hadley Wickham h@w|ckh@m @end|ng |rom gm@||@com
Mon Aug 17 21:25:49 CEST 2020


> | but they won't receive any new
> | features, and we believe that there
> | are now better approaches to solving
> | the same problem.
>
> Is tidyr::pivot_longer this better
> solution?  It is an easier to understand
> version of the now retired and confusing
> (for me) tidyr::gather which at least
> reigned back in 2018 (was that any good
> compared to reshape?).

Yes, and hopefully :)

    library(tidyr)

    tab <- structure(list(
    date = c("2019M08", "2019M09", "2019M10"),
    down = c(0.01709827, 0.02094724, 0.01750911),
    uc = c(0.2653882, 0.2265797, 0.245003),
    up = c(0.7175136, 0.7524731, 0.7374879)),
    class = "data.frame", row.names = c(NA, -3L))

    tab %>% pivot_longer(
      down:up,
      names_to = "direction",
      values_to = "percentage"
    )
    #> # A tibble: 9 x 3
    #>   date    direction percentage
    #>   <chr>   <chr>          <dbl>
    #> 1 2019M08 down          0.0171
    #> 2 2019M08 uc            0.265
    #> 3 2019M08 up            0.718
    #> 4 2019M09 down          0.0209
    #> 5 2019M09 uc            0.227
    #> 6 2019M09 up            0.752
    #> 7 2019M10 down          0.0175
    #> 8 2019M10 uc            0.245
    #> 9 2019M10 up            0.737

<sup>Created on 2020-08-17 by the [reprex
package](https://reprex.tidyverse.org) (v0.3.0)</sup>



-- 
http://hadley.nz



More information about the R-help mailing list