【问题标题】:Transform to wide format from long in R从R中的long转换为宽格式
【发布时间】:2020-10-08 11:51:59
【问题描述】:

我在 R 中有一个如下所示的数据框

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

我希望数据框看起来

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

A_coverageB_Coverage 将在 Excel 中使用公式计算。但我需要帮助的问题是将数据框从宽格式转换为长格式(原始格式)。

我尝试从linked duplicate 实施解决方案,但我仍然遇到困难:

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

这是我的数据的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))

谢谢

【问题讨论】:

    标签: r dataframe dplyr reshape


    【解决方案1】:

    这是一种使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-31
      • 2023-02-25
      • 1970-01-01
      • 2013-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多