Manually Specifying Columns While Pivoting Tables?

I have this data

df<-data.frame(GROUP = c("A", "B", "C"),
               CLASS_1_1 = c(20, 60, 82),
               CLASS_2_1 = c(37, 22, 8),
               CLASS_1_2 = c(15,100,76),
               CLASS_2_2 = c(84, 18,88))

  GROUP CLASS_1_1 CLASS_2_1 CLASS_1_2 CLASS_2_2
1     A        20        37        15        84
2     B        60        22       100        18
3     C        82         8        76        88

I am using this code to pivot the data

library(tidyr)
pivot_longer(df, -GROUP, 
             names_pattern = "(CLASS_.*)_(.*)", 
             names_to = c(".value", "Date"))

# A tibble: 6 x 4
  GROUP Date  CLASS_1 CLASS_2
  <chr> <chr>   <dbl>   <dbl>
1 A     1          20      37
2 A     2          15      84
3 B     1          60      22
4 B     2         100      18
5 C     1          82       8
6 C     2          76      88

Is there some way I can do this without using "names_pattern" and just manually specify the names? As an example:

#pseudocode - does not work?
pivot_longer(df, -GROUP, 
             names_pattern = "c(CLASS_1_1, CLASS_2_1, CLASS_1_2, CLASS_2_2)", 
             names_to = c(".value", "Date"))

Anyone know?

Thanks!!

dat1  %>%  pivot_longer(cols = c("class_1", "class_2"))
1 Like

thank you for your answer!

This topic was automatically closed 42 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.