简体   繁体   中英

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

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     
    (...)   (...)         (...)   

我们可能会使用

as.data.frame(as.table(as.matrix(df1)))
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))

if your more a fan of using data.table , another solution would be to use the melt function to change your data from wide-to-long. Using the example data from Nicolas:

library(data.table)

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_wide <- as.data.table(data)
data_long <- melt(data_wide, id.vars = 'id', variable.name = 'weeks', value.name = 'sales')
data_long
#>     id weeks sales
#>  1: p1    w1    11
#>  2: p2    w1     2
#>  3: p3    w1     3
#>  4: p4    w1     5
#>  5: p5    w1     7
#>  6: p1    w2    13
#>  7: p2    w2     5
#>  8: p3    w2     3
#>  9: p4    w2     6
#> 10: p5    w2     7
#> 11: p1    w3    30
#> 12: p2    w3     2
#> 13: p3    w3     3
#> 14: p4    w3     8
#> 15: p5    w3     7

Created on 2021-11-04 by the reprex package (v2.0.1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM