0

I have a wide R dataframe that I want to partially melt, where the columns all share the same sets of time, and the syntax of the column-names is of a the form (varname_tt_(integer)). Is there a nice way to do the transform below using tidyverse and pivot_longer()? If not, is there some alternative way that's fairly clean?

Here is reproducible example, where I want to transform df into df_partial_melt

df = data.frame(
  name=c("A","B","C"),
  XX_tt_1 = c(10,20,30),
  XX_tt_2 = c(100,200,300),
  YY_tt_1 = c(40, 50, 60),
  YY_tt_2 = c(400, 500, 600)
  )

print(df)
  name XX_tt_1 XX_tt_2 YY_tt_1 YY_tt_2
1    A      10     100      40     400
2    B      20     200      50     500
3    C      30     300      60     600


df_partial_melt = data.frame(
  name=rep(c("A","B","C"), each = 2),
  time = rep(c(1,2), 3),
  XX = c(10, 100, 20, 200, 30, 300),
  YY = c(40,400,50,500,60,600)
)

> print(df_partial_melt)
  name time  XX  YY
1    A    1  10  40
2    A    2 100 400
3    B    1  20  50
4    B    2 200 500
5    C    1  30  60
6    C    2 300 600

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
bigO6377
  • 1,256
  • 3
  • 14
  • 28

0 Answers0