Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partially transposing a data frame

Tags:

r

reshape

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
like image 406
btucker Avatar asked Dec 15 '22 21:12

btucker


1 Answers

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
like image 167
A5C1D2H2I1M1N2O1R2T1 Avatar answered Jan 08 '23 18:01

A5C1D2H2I1M1N2O1R2T1