Home > Software design >  how to use pivot_longer to save to multiple columns?
how to use pivot_longer to save to multiple columns?

Time:11-19

Assume that I have a df similar to this:

# A tibble: 5 x 6
     x1    x2    x3    y1    y2    y3
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1     4     3     2     4     3     2
2     4     3     2     4     3     2
3     4     3     2     4     3     2
4     4     3     2     4     3     2
5     4     3     2     4     3     2

Is there a way to create a tibble with the columns x, y, z in a single pivot_longer comand?, right now I'm using a pivot_longer line for each group of columns but I'm sure there is an easier way to get it.

      x     y     z
   <dbl> <dbl> <dbl>
 1     4     4     1
 2     4     4     1
 3     4     4     1
 4     4     4     1
 5     4     4     1
 6     3     3     2
 7     3     3     2
 8     3     3     2
 9     3     3     2
10     3     3     2
11     2     2     3
12     2     2     3
13     2     2     3
14     2     2     3
15     2     2     3

CodePudding user response:

If you are using pivot_longer:

df %>% pivot_longer(everything(), names_to = c(".value", "z"), names_pattern = "(.)(.)")

CodePudding user response:

You could used reshape from base R:

reshape(inp, direction="long", varying=list(1:3, 4:6), sep="")
    time x1 y1 id
1.1    1  4  4  1
2.1    1  4  4  2
3.1    1  4  4  3
4.1    1  4  4  4
5.1    1  4  4  5
1.2    2  3  3  1
2.2    2  3  3  2
3.2    2  3  3  3
4.2    2  3  3  4
5.2    2  3  3  5
1.3    3  2  2  1
2.3    3  2  2  2
3.3    3  2  2  3
4.3    3  2  2  4
5.3    3  2  2  5

Two "tricks". One is to use sep="" which will split those column names between alpha and numeric. Second is the use of a list argument to varying. If you wanted to drop the first column which identifies the row of origin, then use [-1]. You could also use the v.names vector to name columns, viz:

   reshape(inp, direction="long", varying=list(1:3, 4:6), sep="", v.names=c("X","Y"))[-1]
    X Y id
1.1 4 4  1
2.1 4 4  2
3.1 4 4  3
4.1 4 4  4
5.1 4 4  5
1.2 3 3  1
2.2 3 3  2
3.2 3 3  3
4.2 3 3  4
5.2 3 3  5
1.3 2 2  1
2.3 2 2  2
3.3 2 2  3
4.3 2 2  4
5.3 2 2  5
  • Related