简体   繁体   中英

Transform to wide format from long in R

I have a data frame in R which looks like below

Model Month Demand Inventory
A      Jan     10     20
B      Feb     30     40
A      Feb     40     60

I want the data frame to look

                 Jan        Feb
A_Demand         10         40
A_Inventory      20         60
A_coverage       
B_Demand                    30
B_Inventory                 40
B_coverage     

A_coverage and B_Coverage will be calculated in excel using a formula. But the problem I need help with is to pivot the data frame from wide to long format (original format).

I tried to implement the solution from the linked duplicate but I am still having difficulty:

HD_dcast <- reshape(data,idvar = c("Model","Inventory","Demand"),
                    timevar = "Month", direction = "wide")

Here is a dput of my data:

data <- structure(list(Model = c("A", "B", "A"), Month = c("Jan", "Feb", 
"Feb"), Demand = c(10L, 30L, 40L), Inventory = c(20L, 40L, 60L
)), class = "data.frame", row.names = c(NA, -3L))

Thanks

Here's an approach with dplyr and tidyr , two popular R packages for data manipulation:

library(dplyr)
library(tidyr)
data %>% 
  mutate(coverage = NA_real_) %>%
  pivot_longer(-c(Model,Month), names_to = "Variable") %>%
  pivot_wider(id_cols = c(Model, Variable), names_from = Month ) %>%
  unite(Variable, c(Model,Variable), sep = "_")
## A tibble: 6 x 3
#  Variable      Jan   Feb
#  <chr>       <dbl> <dbl>
#1 A_Demand       10    40
#2 A_Inventory    20    60
#3 A_coverage     NA    NA
#4 B_Demand       NA    30
#5 B_Inventory    NA    40
#6 B_coverage     NA    NA

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