0

I am trying to get newdf from ``olddf. Basically, I want to duplicate and stack columns AandBto allow for columnsCandD```` to be stacked in a single column. Sorry for the bad explanation, essentially, I am stacking C and D into a single column and need to repeat A and B to account for the repetitions, thank you.

olddf <- data.frame('A' = c('Z1','Z2','Z3'), 
           'B' = c(100, 200, 500),
           'C' = c(90, 50, 60),
           'D' = c(NA, 50, NA))

newdf <- data.frame('A' = c('Z1','Z2','Z3','Z1','Z2','Z3'), 
                    'B' = c(100, 200, 500, 100, 200, 500),
                    'CD' = c(90, 50, 60, NA, 50, NA))

1 Answers1

2

tidyverse solution:

olddf |> 
  pivot_longer(names_to="col", values_to="CD", C:D) |> 
  arrange(col, A) |> 
  select(-col)

Output:

# A tibble: 6 x 3
  A         B    CD
  <chr> <dbl> <dbl>
1 Z1      100    90
2 Z2      200    50
3 Z3      500    60
4 Z1      100    NA
5 Z2      200    50
6 Z3      500    NA
geoff
  • 942
  • 5
  • 13