0

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.

2
  • 3
    Please provide your data in reproducible form. i.e. display the result of dput(yourdata) May 10, 2014 at 13:38
  • Data in a reproducible form below. Will keep it in mind next for time.
    – DJJ
    May 10, 2014 at 14:05

1 Answer 1

6

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)
1
  • Thanks for having provided data.
    – DJJ
    May 10, 2014 at 14:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.