Pergunta

I would like to transpose the following table

+---------+----------+------+-------+
|  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   |
+---------+----------+------+-------+

To something like :

+---------+----------+------+--------+
|  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   |
+---------+----------+------+--------+

I tried to transpose using reshape but the main difficulty has been to keep the year in the long position.

Foi útil?

Solução

Here's a way to do it using reshape2. The trick is to get the data into long format first.

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)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top