Search code examples
rtidyverse

Move a set of columns to rows of existing columns in R


Suppose I have a dataframe with four columns and each column has exactly the same structure. I'm trying to move columns 3 and 4 as rows of columns 1 and 2, but cannot figure out how. Here's a reproducible example. I want to append values in columns c and d as rows to columns a and b. Thank you!

> df
# A tibble: 2 × 4
      a     b     c     d
  <dbl> <dbl> <dbl> <dbl>
1     1     2     3     4
2     1     2     3     4

> df1
# A tibble: 4 × 2
      a     b
  <dbl> <dbl>
1     1     2
2     1     2
3     3     4
4     3     4

Solution

  • Try

    list2DF(split.default(unlist(df), rep(letters[1:2], each = 2)))
    

    -output

      a b
    1 1 2
    2 1 2
    3 3 4
    4 3 4