0

I am looking for something like a partial pivot_longer. The example below works, but it is not elegant, and gets messy when I have more columns _1, _2, _n. Anyone boRed by home-office looking for a challenge?

library(tidyr)
library(dplyr)
#> 
#> Attache Paket: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
dt = tribble(
  ~pat, ~bmi_0, ~score_0, ~bmi_5, ~score_5,
  "a",25,30, 28, 43,
  "b",27,20, 21, 25,
  "c",28,21, 23, 21
)

dt_0 = dt %>% select(pat, bmi = bmi_0, score = score_0) %>% mutate(when="0")
dt_5 = dt %>% select(pat, bmi = bmi_5, score = score_5) %>% mutate(when="5")
# Ok, this could be combined...
bind_rows(dt_0, dt_5)
#> # A tibble: 6 x 4
#>   pat     bmi score when 
#> * <chr> <dbl> <dbl> <chr>
#> 1 a        25    30 0    
#> 2 b        27    20 0    
#> 3 c        28    21 0    
#> 4 a        28    43 5    
#> 5 b        21    25 5    
#> 6 c        23    21 5

Dieter Menne
  • 10,076
  • 44
  • 67
  • 1
    Isn't this [Reshaping multiple sets of measurement columns (wide format) into single columns (long format)](https://stackoverflow.com/questions/12466493/reshaping-multiple-sets-of-measurement-columns-wide-format-into-single-columns)? – Henrik Apr 10 '20 at 10:53

1 Answers1

0

Oh, no, this was almost trivial:

dt %>% pivot_longer(
  -pat,
  names_to = c(".value", "when"), 
  names_sep = "_"
)

Sorry for asking, maybe someone has a use for it.

Dieter Menne
  • 10,076
  • 44
  • 67