0

想象一下下面的df:

   quar              metier    kweffort trips
   <int>               <chr>       <dbl> <int>
1      1 OTB_DEF_100-119_0_0  12866.9022     6
2      1   OTB_DEF_70-99_0_0  13546.3839    11
3      1   OTB_MCD_70-99_0_0   2052.9117     2
4      1 TBB_DEF_100-119_0_0   4496.7492     1
5      1   TBB_DEF_70-99_0_0 384167.3136    69
6      1    TBB_DEF_G120_0_0   7260.1340     1
7      2 OTB_DEF_100-119_0_0  78069.8550    19
8      2   OTB_DEF_70-99_0_0  14333.0972    12
9      2    OTB_DEF_G120_0_0    859.0463     1
10     2   OTB_MCD_70-99_0_0  22528.3388    19

如何使用 spread 来获取列中包含 quar 并且 kweffort 和 trips 作为值的表?

希望它看起来像这样:

metier                 quar 1                      quar 2    quar 3    quar 4
OTB_DEF_100-119_0_0    trip value kweffort value   ...       ...       ...
4

2 回答 2

1

我们可以unite将“kweffort”和“trips”转换为单个列,然后spread转换为“wide”格式。

library(tidyr)
df1 %>%
    unite(kweffort_trips, kweffort, trips, sep=", ") %>% 
    spread(quar, kweffort_trips, sep="")
于 2016-10-25T15:35:28.580 回答
0

不使用基础 R:

library(reshape2)
df$trips.kweffort <- paste('trips', df$trips, 'kweffort', df$kweffort)
dcast(df, metier~quar, value.var = 'trips.kweffort')
于 2016-10-25T17:40:35.187 回答