Search code examples
rreshape

wide to long using column index r


I have a df:

df1 <- data.frame(ID = c('a', 'b', 'c', 'c1', 'd', 'e', 'f', 'g', 'h', 'h1'),
                  var2 = c(7, 9, 2, 4, 3, 6, 8, 2, 1, 2),
                  var3 = c(21, 50, 40, 30, 29, 45, 33, 51, 70, 46),
                  var4 = c(1, 5, 2, 4, 1, 2, 3, 3, 5, 1))

Which I want to convert from wide to long format. I need to do this repeatedly for a number of different dataframes with different column names and numbers. The columns to convert will always be between the second and last column, using something like this:

data_long <- gather(df1, ID, num, df1[c(2:ncol(df1))], factor_key=TRUE)

So that the output looks like the following:

> data_long
     ID num
1  var2   7
2  var2   9
3  var2   2
4  var2   4
5  var2   3
6  var2   6
7  var2   8
8  var2   2
9  var2   1
10 var2   2
11 var3  21
12 var3  50
13 var3  40
14 var3  30
15 var3  29
16 var3  45
17 var3  33
18 var3  51
19 var3  70
20 var3  46
21 var4   1
22 var4   5
23 var4   2
24 var4   4
25 var4   1
26 var4   2
27 var4   3
28 var4   3
29 var4   5
30 var4   1

Solution

  • Is it what you want?

    tidyr::pivot_longer(df1, -ID)
    
    # A tibble: 30 × 3
       ID    name  value
       <chr> <chr> <dbl>
     1 a     var2      7
     2 a     var3     21
     3 a     var4      1
     4 b     var2      9
     5 b     var3     50
     6 b     var4      5
     7 c     var2      2
     8 c     var3     40
     9 c     var4      2
    10 c1    var2      4
    # ℹ 20 more rows
    # ℹ Use `print(n = ...)` to see more rows
    

    Or even pivot_longer(df1, -1) if ID column name is also subject to change