0

I want to do this but the exact opposite. So say my dataset looks like this:

ID X_1990 X_2000 X_2010 Y_1990 Y_2000 Y_2010
A 1 4 7 10 13 16
B 2 5 8 11 14 17
C 3 6 9 12 15 18

but with a lot more measure variables (i.e. also Z_1990, etc.). How can I get it so that the year becomes a variable and it will keep the different measures, like this:

ID Year X Y
A 1990 1 10
A 2000 4 13
A 2010 7 16
B 1990 2 11
B 2000 5 14
B 2010 8 17
C 1990 3 12
C 2000 3 15
C 2010 9 18
Dylan
  • 83
  • 1
  • 5
  • So sorry, I didn't know how to enter tables, but I just fixed it. Let me know if I need to add anything else! – Dylan Sep 26 '21 at 04:12

1 Answers1

0

You may use pivot_longer with names_sep argument.

tidyr::pivot_longer(df, cols = -ID, names_to = c('.value', 'Year'), names_sep = '_')

#  ID    Year      X     Y
#  <chr> <chr> <int> <int>
#1 A     1990      1    10
#2 A     2000      4    13
#3 A     2010      7    16
#4 B     1990      2    11
#5 B     2000      5    14
#6 B     2010      8    17
#7 C     1990      3    12
#8 C     2000      6    15
#9 C     2010      9    18

data

It is easier to help if you provide data in a reproducible format

df <- structure(list(ID = c("A", "B", "C"), X_1990 = 1:3, X_2000 = 4:6, 
    X_2010 = 7:9, Y_1990 = 10:12, Y_2000 = 13:15, Y_2010 = 16:18), 
row.names = c(NA, -3L), class = "data.frame")
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • how would you add more variables in "cols" (not only by ID). Would it be cols = -c(ID, others)? In this case, it doesn't work me. Thank you! – vog Nov 28 '22 at 16:02