如何按组重新整形data.frame

时间:2014-05-10 13:33:07

标签: r dataframe

我想转置下表

+---------+----------+------+-------+
|  var    |  Year    |  A   |  B    |
+---------+----------+ -----+-------+
| Mean    |  2006    | 1.3  | 4.6   |
| Median  |  2006    | 1.4  | 4.1   |
| Mean    |  2007    | 3.6  | 5.5   | 
| Median  |  2007    | 4.0  | 5.5   |
| Mean    |  2008    | 5.5  | 4.0   |  `  
| Median  |  2008    | 5.5  | 5.1   |
+---------+----------+------+-------+

类似于:

+---------+----------+------+--------+
|  var    |  Year    | Mean | Median |
+---------+----------+ -----+--------+
|   A     |   2006   | 1.3  |  1.4   |
|         |   2007   | 3.6  |  4.0   |
|         |   2008   | 5.5  |  5.5   | 
|   B     |   2006   | 5.5  |  4.6   |
|         |   2007   | 5.5  |  5.5   |  `  
|         |   2008   | 5.1  |  5.1   |
+---------+----------+------+--------+

我尝试使用重塑进行转置,但主要的困难是将年份保持在多头位置。

1 个答案:

答案 0 :(得分:6)

以下是使用reshape2执行此操作的方法。诀窍是首先将数据转换成长格式。

library(reshape2)
d <- data.frame(var=c("Mean", "Median"),
                Year=sort(rep(2006:2008,2)),
                A=1:6, B=11:16)
d_melted <- melt(d, measure.vars=c("A", "B"))
dcast(d_melted, variable + Year ~ var)