0

I have a data frame like this that was produced using the 'reshape' function. I was wondering whether there was an 'opposite' to the reshape function that allows me to turn a data frame from wide to long based on multiple columns?

I have this:

ID     Date.1       Site.1     Brand.1   Date.2      Site.2   Brand.2
A-001  2021-05-21   Place A    Brand A   2021-06-01  Place B  Brand C 
A-002  2021-05-19   Place D    Brand A   2021-05-19  Place D  Brand D

But would like this:

ID    Seq   Date        Site     Brand
A-001 1     2021-05-21  Place A  Brand A
A-001 2     2021-06-01  Place B  Brand C
A-002 1     2021-05-19  Place D  Brand A
A-002 2     2021-05-19  Place D  Brand D

Thanks!

Dieu94
  • 371
  • 1
  • 11

1 Answers1

1

We can use pivot_longer

library(tdyr)
pivot_longer(df1, cols = -ID, names_to = c(".value", "Seq"), names_sep = "\\.")

-output

# A tibble: 4 x 5
#  ID    Seq   Date       Site    Brand  
#  <chr> <chr> <chr>      <chr>   <chr>  
#1 A-001 1     2021-05-21 Place A Brand A
#2 A-001 2     2021-06-01 Place B Brand C
#3 A-002 1     2021-05-19 Place D Brand A
#4 A-002 2     2021-05-19 Place D Brand D

Or using reshape from base R

reshape(df1, direction = 'long', varying = list(c(2, 5), c(3, 6), c(4, 7)))

data

df1 <- structure(list(ID = c("A-001", "A-002"), Date.1 = c("2021-05-21", 
"2021-05-19"), Site.1 = c("Place A", "Place D"), Brand.1 = c("Brand A", 
"Brand A"), Date.2 = c("2021-06-01", "2021-05-19"), Site.2 = c("Place B", 
"Place D"), Brand.2 = c("Brand C", "Brand D")), class = "data.frame", 
     row.names = c(NA, 
-2L))
akrun
  • 874,273
  • 37
  • 540
  • 662