简体   繁体   English

从 R 中的长转换为宽格式

[英]Transform to wide format from long in R

I have a data frame in R which looks like below我在 R 中有一个数据框,如下所示

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. A_coverageB_Coverage将使用公式在 excel 中计算。 But the problem I need help with is to pivot the data frame from wide to long format (original format).但我需要帮助的问题是 pivot 数据帧从宽格式到长格式(原始格式)。

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:这是dput的数据的输入:

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:这是一种使用dplyrtidyr的方法,这两个流行的 R 包用于数据操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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