btucker
btucker

Reputation: 347

Partially transposing a data frame

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

Upvotes: 4

Views: 2023

Answers (2)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

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

Upvotes: 7

MrFlick
MrFlick

Reputation: 206197

This is a good place to use the reshape2 library. You can just do

library(reshape2)
dcast(dd, A+B~C)

to get

   A  B c1   c2 c3
1 a1 b1 d1   d2 d3
2 a2 b2 d1 <NA> d3

as desired.

Upvotes: 5

Related Questions