Sort of transposing a table

hit wrong key
hit wrong key
hit wrong key
hit wrong key

I have a table that looks like this:

suppressPackageStartupMessages(library(tidyverse))
tbl1 <- tibble::tribble(~datetime, ~systolic, ~diastolic,
lubridate::as_datetime("2017-03-25 17:00:00"), 104, 78,
lubridate::as_datetime("2017-03-26 04:00:00"), 107, 75,
lubridate::as_datetime("2017-03-26 17:15:00"), 107, 84
)
tbl1
#> # A tibble: 3 x 3
#>              datetime systolic diastolic
#>                <dttm>    <dbl>     <dbl>
#> 1 2017-03-25 13:00:00      104        78
#> 2 2017-03-26 00:00:00      107        75
#> 3 2017-03-26 13:15:00      107        84

But it would be easier to plot the way I want if it looked like this:

tbl2 <- tibble::tribble(~datetime, ~kind, ~pressure,
lubridate::as_datetime("2017-03-25 17:00:00"), "systolic", 104,
lubridate::as_datetime("2017-03-25 17:00:00"), "diastolic", 78,
lubridate::as_datetime("2017-03-26 04:00:00"), "systolic", 107,
lubridate::as_datetime("2017-03-26 04:00:00"), "diastolic", 75,
lubridate::as_datetime("2017-03-26 17:15:00"), "systolic", 107,
lubridate::as_datetime("2017-03-26 17:15:00"), "diastolic", 84
)
tbl2
#> # A tibble: 6 x 3
#>              datetime      kind pressure
#>                <dttm>     <chr>    <dbl>
#> 1 2017-03-25 13:00:00  systolic      104
#> 2 2017-03-25 13:00:00 diastolic       78
#> 3 2017-03-26 00:00:00  systolic      107
#> 4 2017-03-26 00:00:00 diastolic       75
#> 5 2017-03-26 13:15:00  systolic      107
#> 6 2017-03-26 13:15:00 diastolic       84

I can easily process tbl1 to create tbl2, but is there some way to get dplyr (or?) to do the work for me with
a declarative looking statement?

Thanks,
Dan

tbl3 <- gather(tbl1, "kind", "pressure", -datetime)
all.equal(tbl2, tbl3)
# [1] TRUE

"Sort of transposing": this operation is called: gather (vs spread, those are tidyr functions), or melt (vs cast, in reshape2 or data.table parlance for instance), or unpivot (vs pivot, that'd be typical Excel jargon), or format to long (vs wide), or stack (vs unstack).

A good reference is: http://vita.had.co.nz/papers/tidy-data.html (and that explains why plotting looks easier after melting, it's because, by design, the tidyverse works better with long data).

4 Likes

Thank you, more things to dig into....

It reminds me of a mythical software app:

"Our application is very user friendly... it just has one button... and we ship it with that button already pressed!"