0

This question is similar to many previous posts, but not exactly (at least from my understanding, which is limited i R-programming). I have a dataset with k countries over N years. For each country I have K variables (all being the same for all k countries).

The dataset is a wide panel that looks approximately like this:

Country Variable   Year1          Year2      ...       YearN
C1         V1        V1_C1_Y1     V1_C1_Y2         V1_C1_YN
C1         V2        V2_C1_Y1     V2_C1_Y2         V2_C1_YN
C1         V3        V3_C1_Y1     V3_C1_Y2         V3_C1_YN
.
.
.
C1        VK         VK_C1_Y1     VK_C1_Y2         VK_C1_YN
C2         V1        V1_C2_Y1     V1_C2_Y2         V1_C2_YN
C2         V2        V2_C2_Y1     V2_C2_Y2         V2_C2_YN
.
.
.
C2         VK        VK_C2_Y1     VK_C2_Y2                VK_C2_YN
C3         V1        V1_C3_Y1     V1_C3_Y2                V1_C3_YN
.
.
Ck         V1        V1_Ck_Y1     V1_Ck_Y2                V1_Ck_YN
.
.
.
Ck         VK        VK_Ck_Y1     VK_Ck_Y2                VK_Ck_YN

The country names are given as actual names: Algeria, Argentina, ..., Zimbabwe. The variables are Budget balance, GDP, ... with a total of K variables.

The problem is, I want the dataset to be a long panel:

Country Year Variable1    Variable2 . . . . VariableK
C1       Y1  V1_C1_Y1     V2_C1_Y1        VK_C1_Y1
.
.
C1       YN  V1_C1_YN     V2_C1_YN        VK_C1_YN
C2       Y1  V1_C2_Y1     V2_C2_Y1        VK_C2_Y1
.
.
C2       YN  V1_C2_YN     V2_C2_YN        VK_C2_YN
.
.
Ck       Y1  V1_Ck_Y1     V2_Ck_Y1       VK_Ck_Y1
.
.
Ck       YN  V1_Ck_YN     V2_Ck_YN      VK_Ck_YN

I don't understand how to reshape the dataset to the long format.

Bas H
  • 2,114
  • 10
  • 14
  • 23
Thomas.LRV
  • 23
  • 6
  • 1
    I think this is actually a double-pivot. In `tidyr`, try `pivot_longer(quux, -c(Country, Variable), names_to = "Year") %>% pivot_wider(c(Country, Year), names_from = "Variable", values_from = "value")`. In `reshape2`, try `melt(quux, id.vars = c("Country", "Variable"), variable.name = "Year") |> dcast(Country + Year ~ Variable, value.var = "value")`. – r2evans Apr 13 '23 at 12:27

0 Answers0