[R] Reshape from long to wide

Gabor Grothendieck ggrothendieck at gmail.com
Tue Mar 20 05:37:30 CET 2012


On Mon, Mar 19, 2012 at 7:01 PM, aly <alyabadia at gmaaaail.com> wrote:
>
> Hi,
>
> I'm a total beginner in R and this question is probably very simple but I've
> spent hours reading about it and can't find the answer. I'm trying to
> reshape a data table from long to wide format. I've tried reshape() and
> cast() but I get error messages every time and I can't figure why. In my
> data, I have the length of two fish from each family. My data table (called
> fish) looks like this:
>
> family  length
> 14      18
> 14      7
> 15      7
> 15      21
> 17      50
> 17      21
> 18      36
> 18      21
> 20      36
> 20      42
> 24      56
> 24      42
> 25      43
> 25      56
> 27      15
> 27      42
> 28      7
> 28      42
> 29      56
> 29      49
>
> I want it to look like this:
>
> family kid1 kid2
> 14      18      7
> 15      7       21
> 17      50      21
> 18      36      21
> 28      36      42
> 24      56      42
> 25      43      56
> 27      15      42
> 28      7       42
> 29      56      49

Here are a few solutions.  First create fish2 from fish:

fish2 <- data.frame(fish, kid = c("kid1", "kid2"))

# 1
xtabs(length ~ family + kid, DF2)

# 2
reshape(data = DF2, dir = "wide", timevar = "kid", idvar = "family")

# 3
with(fish2, data.frame(family = unique(family),
   kid1 = length[kid == "kid1"],
   kid2 = length[kid == "kid2"]))

# 4
library(reshape)
cast(family ~ kid, data = fish2, value = "length")

# 5
library(reshape2)
dcast(family ~ kid, data = fish2, value.var = "length")

--
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list