【问题标题】:Reshaping data to add new columns for each value of one variable重塑数据以为一个变量的每个值添加新列
【发布时间】:2018-02-23 20:20:35
【问题描述】:

目前我已经能够让我的数据看起来像:

          date           category    revenue    cost
     20150100               1      2670935 1290161.8
     20150200               1      2487379 1201022.2
     20150300               1      2663918 1244556.4
     20150400               1      2557039 1208289.3
     20150500               1      2372128 1026402.6
     20150600               1      2981372  919436.4
     20150100               2      2670935 1290161.8
     20150200               2      2487379 1201022.2
     20150300               2      2663918 1244556.4
     20150400               2      2557039 1208289.3
     20150500               2      2372128 1026402.6
     20150600               2      2981372  919436.4

我想将其重塑为如下所示(带有额外的 cat2 列):

          date           category  cat1.revenue    cat1.cost
     20150100               1      2670935         1290161.8
     20150200               1      2487379         1201022.2
     20150300               1      2663918         1244556.4
     20150400               1      2557039         1208289.3
     20150500               1      2372128         1026402.6
     20150600               1      2981372          919436.4

我不知道如何使用 dplyr 或其他数据整理包来让我的数据看起来像这样。

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    一种可能的解决方案是使用gatherunitespread 作为

    library(tidyverse)
    df %>% gather(key, value, -date, -category) 
     %>% unite(combined, key, category, sep = "_cat") %>%
    spread(combined, value)
    
    #      date cost_cat1 cost_cat2 revenue_cat1 revenue_cat2
    #1 20150100 1290161.8 1290161.8      2670935      2670935
    #2 20150200 1201022.2 1201022.2      2487379      2487379
    #3 20150300 1244556.4 1244556.4      2663918      2663918
    #4 20150400 1208289.3 1208289.3      2557039      2557039
    #5 20150500 1026402.6 1026402.6      2372128      2372128
    #6 20150600  919436.4  919436.4      2981372      2981372
    

    数据:

    df <- read.table( text = "date           category    revenue    cost
    20150100               1      2670935 1290161.8
    20150200               1      2487379 1201022.2
    20150300               1      2663918 1244556.4
    20150400               1      2557039 1208289.3
    20150500               1      2372128 1026402.6
    20150600               1      2981372  919436.4
    20150100               2      2670935 1290161.8
    20150200               2      2487379 1201022.2
    20150300               2      2663918 1244556.4
    20150400               2      2557039 1208289.3
    20150500               2      2372128 1026402.6
    20150600               2      2981372  919436.4", 
    header = T, stringsAsFactor = F)
    

    【讨论】:

      猜你喜欢
      • 2016-07-23
      • 2021-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-19
      • 1970-01-01
      • 2017-03-10
      • 1970-01-01
      相关资源
      最近更新 更多