Partially transposing a data frame

r, reshape

Solution

In base R, you can use `reshape()`:

reshape(mydf, direction = "wide", idvar = c("A", "B"), timevar = "C")
#    A  B D.c1 D.c2 D.c3
# 1 a1 b1   d1   d2   d3
# 4 a2 b2   d1 <NA>   d3

You can also use `tidyr` and `dplyr` together, like this:

library(dplyr)
# devtools::install_github("hadley/tidyr")
library(tidyr)
mydf %>% group_by(A, B) %>% spread(C, D)
# Source: local data frame [2 x 5]
# 
#    A  B c1 c2 c3
# 1 a1 b1 d1 d2 d3
# 2 a2 b2 d1 NA d3

Problem

I have a data frame with data like this: ``` A B C D a1 b1 c1 d1 a1 b1 c2 d2 a1 b1 c3 d3 a2 b2 c1 d1 a2 b2 c3 d3 ``` How would I go about transforming that into? ``` A B c1 c2 c3 a1 b1 d1 d2 d3 a2 b2 d1 d3 ```

Original source