Reshape data frames: wide and long format

Using stack() for data frames with a simple structure

Wide format -> long format

  values   ind
1      3 cond1
2      3 cond1
3     10 cond1
4      2 cond1
5      9 cond3
6     10 cond3
7      5 cond3
8      3 cond3
'data.frame':   8 obs. of  2 variables:
 $ values: int  3 3 10 2 9 10 5 3
 $ ind   : Factor w/ 2 levels "cond1","cond3": 1 1 1 1 2 2 2 2

Long format -> wide format

  cond1 cond3
1     3     9
2     3    10
3    10     5
4     2     3
  values   ind IVnew DVnew
1      3 cond1     A   125
2      3 cond1     A   106
3     10 cond1     B   141
4      2 cond1     A   108
5      9 cond3     A   182
6     10 cond3     B   135
    A   B
1 125 141
2 106 135
3 108 177
4 182 180

Using reshape() for more complex data frames

One within variable

Simulate data

  id IVbtw DV_t1 DV_t2 DV_t3
1  1     A -0.30 -1.03  1.84
2  2     B -1.47 -0.73  1.15
3  3     A -2.07 -0.63 -0.14
4  4     B -1.22 -1.69  2.25
   id IVbtw IVwth    DV
1   1     A     1 -0.30
5   1     A     2 -1.03
9   1     A     3  1.84
2   2     B     1 -1.47
6   2     B     2 -0.73
10  2     B     3  1.15
3   3     A     1 -2.07
7   3     A     2 -0.63
11  3     A     3 -0.14
4   4     B     1 -1.22
8   4     B     2 -1.69
12  4     B     3  2.25

Wide format -> long format

      id IVbtw IVwth    DV
1.A.1  1     A     1 -0.30
1.A.2  1     A     2 -1.03
1.A.3  1     A     3  1.84
2.B.1  2     B     1 -1.47
2.B.2  2     B     2 -0.73
2.B.3  2     B     3  1.15
3.A.1  3     A     1 -2.07
3.A.2  3     A     2 -0.63
3.A.3  3     A     3 -0.14
4.B.1  4     B     1 -1.22
4.B.2  4     B     2 -1.69
4.B.3  4     B     3  2.25
[1] TRUE

Long format -> wide format

  id IVbtw  DV.1  DV.2  DV.3
1  1     A -0.30 -1.03  1.84
2  2     B -1.47 -0.73  1.15
3  3     A -2.07 -0.63 -0.14
4  4     B -1.22 -1.69  2.25

Two within variables

Simulate data

Wide format -> long format

    id IV1 IV2-1 IV2-2
1.1  1   1  8.85  7.47
2.1  2   1  7.41 14.34
3.1  3   1  9.79 12.42
4.1  4   1  9.76  7.75
1.2  1   2 14.64 14.19
2.2  2   2 14.38 14.07
3.2  3   2 14.11 16.56
4.2  4   2 12.88 14.83
1.3  1   3 12.39 15.51
2.3  2   3 12.24 14.94
3.3  3   3 11.61 14.91
4.3  4   3 12.58 17.74
      id IV1 IV2    DV
1.1.1  1   1   1  8.85
2.1.1  2   1   1  7.41
3.1.1  3   1   1  9.79
4.1.1  4   1   1  9.76
1.2.1  1   2   1 14.64
2.2.1  2   2   1 14.38

Long format -> wide format

[1] TRUE

Useful packages

Package tidyr provides functions pivot_longer() and pivot_wider() for an alternative approach to reshaping data frames that can be integrated into a dplyr based workflow.

Get the article source from GitHub

R markdown - markdown - R code - all posts