将一列传播到R中的多列(Spread?,Reshape?)

时间:2018-04-17 01:20:51

标签: r subset reshape spread

我想通过将(Spread?,Reshape?)分配到月份列来摆脱下表中的Station.ID列,以便获取Jan_323,Feb_323,...,Jan_452,Feb_452等列,...

 Have:

 Station.ID  Year    Jan   Feb    Mar   Apr  May   Jun
 323         1995    31.3  25.2   19.0   15.0 ..    .. 
 323         1996    28.0  20.2   17.5   14.0 ..    ..
 323         ...     ..    ..     ..     ..   ..    ..
 ...         ...     ..    ..     ..     ..   ..    ..
 452         1995    16.2  ..     ..     ..   ..    ..
 452         1996    14.3  ..     ..     ..   ..    ..
 452         ...     ..    ..     ..     ..   ..    ..
 ..          ...     ..    ..     ..     ..

 Want:

 Year    Jan_323  Feb_323   Mar_323  ...  Jan_452   Feb_452   Mar_452   ...
 1995     31.3     25.2     19.0     ...   16.2       ...       ...     ...
 1996     28.0      ...       ...    ...   14.3       ...       ...     ...
 1997     ...       ...       ...    ...   ...        ...       ...     ...    
 1998     ...       ...       ...    ...   ...        ...       ...     ...
 ....     ...       ...       ...    ...   ...        ...       ...     ...

1 个答案:

答案 0 :(得分:0)

我们可以在Sale Price进入' long'之后使用spread格式

gather

数据

library(tidyverse)
gather(df1, key, value, -Station.ID, -Year) %>% 
      unite(Station.ID, key, Station.ID) %>% 
      mutate(Station.ID = factor(Station.ID, levels = unique(Station.ID))) %>%
      spread(Station.ID, value)
#   Year Jan_323 Jan_452 Feb_323 Feb_452 Mar_323 Mar_452 Apr_323 Apr_452 May_323 May_452 Jun_323 Jun_452
#1 1995    31.3    16.2    25.2    20.1    19.0    31.2    15.0    12.2    12.0    12.5    10.1    22.1
#2 1996    28.0    14.3    20.2    23.1    17.5    34.2    14.0    14.2    10.5    13.5    12.2    19.1
#3 1997    20.2    20.1    22.1    22.1    31.2    32.2    12.2    13.2    12.5    11.5    22.1    18.1