0

I have the following dataset:

   absences  G1 G2 G3
1          6  5  6  6
2          4  5  5  6
3         10  7  8 10
4          2 15 14 15
5          4  6 10 10

Each of the columns G1, G2 and G3 are different measurement of a given variable of interest. I would like to have another dataset like with 3 columns: absences, a key indicating which measurement is that and the value. For instance, stacking the columns above.

I have taken a look online and the gather() function from tidyr seems the way to go. However, I couldn't understand really well its syntax. Could anyone help me? Thank you a lot in advance!

Raul Guarini Riva
  • 651
  • 1
  • 10
  • 20

1 Answers1

1
library(tidyr)

dataset <- read.table(text = '   absences  G1 G2 G3
1          6  5  6  6
2          4  5  5  6
3         10  7  8 10
4          2 15 14 15
5          4  6 10 10',
                      header = TRUE)

gather(data = dataset,
       key = "G",
       value = "value",
       -absences)
#>    absences  G value
#> 1         6 G1     5
#> 2         4 G1     5
#> 3        10 G1     7
#> 4         2 G1    15
#> 5         4 G1     6
#> 6         6 G2     6
#> 7         4 G2     5
#> 8        10 G2     8
#> 9         2 G2    14
#> 10        4 G2    10
#> 11        6 G3     6
#> 12        4 G3     6
#> 13       10 G3    10
#> 14        2 G3    15
#> 15        4 G3    10

Created on 2019-05-23 by the reprex package (v0.3.0)

Hope this helps.

yarnabrina
  • 1,561
  • 1
  • 10
  • 30