Home > Net >  How do I transform a data into long/horizontal format?
How do I transform a data into long/horizontal format?

Time:11-05

As the question's subject suggests, I have the following dataset, which is presumably cross-sectional. See code beneath,

   W1        W2        W3        () 
P1  11  12  10  8   13  12  14  21  6   
P2  7   6   3   2   7   1   6   3   3   
P3  7   11  8   9   10  8   7   13  12  
P4  12  8   13  5   9   6   9   13  13  
P5  8   5   13  11  6   7   9   14  9   
P6  3   3   2   7   6   3   8   6   6   
6 rows | 1-10 of 52 columns

Given we have the variable W for week and P for Product. My question: How can I transform my data set in a manner that I have long data set with the variables: Time (in weeks) Product (Sales) like this:

Time Product_Number Product_Sales
    W1      P1             20
    W2      P2              5     
    (...)   (...)         (...)   

CodePudding user response:

We may use

as.data.frame(as.table(as.matrix(df1)))

CodePudding user response:

data <- data.frame(id=c("p1","p2","p3","p4","p5"),
                   w1=c(11,2,3,5,7),
                   w2=c(13,5,3,6,7),
                   w3=c(30,2,3,8,7))

data

library(dplyr)
library(tidyr)

data %>% pivot_longer(cols = c(2:4))
  • Related