Grab columns of data frame and put them as new rows

Hello,

sorry if I am asking something obvious :slight_smile:

The data frame:

df <- tribble(
    ~a, ~b, ~c, ~d,
    "item1", 10, "item2", 20,
    "item3", 30, "item4", 40
  )

> df
# A tibble: 2 × 4
  a         b c         d
  <chr> <dbl> <chr> <dbl>
1 item1    10 item2    20
2 item3    30 item4    40

I want to grab columns c , d and put them at the bottom of data frame as new records, so the final df would look like this:

# A tibble: 4 × 2
  a         b
  <chr> <dbl>
1 item1    10
2 item3    30
3 item2    20
4 item4    40

How to achieve this please, preferably in tidyverse way?

Here is one method.

library(tidyverse)
df <- tribble(
  ~a, ~b, ~c, ~d,
  "item1", 10, "item2", 20,
  "item3", 30, "item4", 40
)
Part1 <- select(df, a:b)
Part2 <- select(df, c:d)
colnames(Part2) <- colnames(Part1)
NewDF <- bind_rows(Part1, Part2)
NewDF
#> # A tibble: 4 × 2
#>   a         b
#>   <chr> <dbl>
#> 1 item1    10
#> 2 item3    30
#> 3 item2    20
#> 4 item4    40

Created on 2024-01-29 with reprex v2.0.2

@FJCC, perfect. I understand. Thank you very much for your help, I appreciate it.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.