[R] RE SHAPE package question.

David Hewitt dhewitt37 at gmail.com
Mon Aug 4 17:59:28 CEST 2008


This is a useful tip, but there is some confusion in the thread that makes it
hard to follow. Just clarifying, I hope, so that folks can easily follow it
in the future.

The original posting had a set of encounter histories with descriptions that
did not match the histories. There were 2 males and 1 female for the first
history and 4 males for the second history (but the descriptions indicated
that there was 1 male and 3 females). In the example subsequently posted,
the first history is the same but the second history includes 3 males and 1
female (the opposite of what was originally described):



> I am sorry but here is an example
>> test
>> t1 t2 t3 t4 M F id
>> 1  1  0  0  0 1 0  1
>> 2  1  0  0  0 1 0  1
>> 3  1  0  0  0 0 1  1
>> 4  1  0  1  1 1 0  1
>> 5  1  0  1  1 1 0  1
>> 6  1  0  1  1 1 0  1
>> 7  1  0  1  1 0 1  1
> 

Working from the provided example above (3 males and 1 female for the second
history), all that is needed to condense this set of histories is the
following (I dropped the ID column because I didn't see why it was
included):

> library(reshape)
> tmp1 <- read.table("test.txt", header=T)
> tmp2 <- melt(tmp1, measure.var=c("M", "F"))
> condensed <- cast(tmp2, t1 + t2 + t3 + t4 ~ variable,
     fun.aggregate=sum)
> condensed
  t1 t2 t3 t4 M F
1  1  0  0  0 2 1
2  1  0  1  1 3 1

Once "M" and "F" are included in the 'melt' command they cannot be used in
the 'cast' command.

A more compact solution comes from 'recast':

> tmp3 <- recast(tmp1, t1 + t2 + t3 + t4 ~ variable,
>      fun.aggregate=sum, measure.var=c("M", "F"))
> tmp3
  t1 t2 t3 t4 M F
1  1  0  0  0 2 1
2  1  0  1  1 3 1


-----
David Hewitt
Research Fishery Biologist
USGS Klamath Falls Field Station (USA)
-- 
View this message in context: http://www.nabble.com/RESHAPE-package-question.-tp18792801p18814133.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list