[R] Presence/ absence data from matrix to single column

Jim Lemon jim at bitwrit.com.au
Sun Oct 7 02:36:12 CEST 2012


On 10/07/2012 01:03 AM, agoijman wrote:
> I've been trying to reshape this database but haven't succeed at it. I tried
> using loops but can't get it right. I just want to reshape my database from
> this matrix, to the one below, with only one column of data.
>
> Year	Route	Point	Sp1	Sp2	Sp3
> 2004	123	123-1	0	1	0
> 2004	123	123-2	0	1	1
> 2004	123	123-10	1	1	0
>
> What I want:
>
> Year	Route	Point			
> 2004	123	123-1	Sp1	0	
> 2004	123	123-2	Sp1	0	
> 2004	123	123-10	Sp1	1	
> 2004	123	123-1	Sp2	1	
> 2004	123	123-2	Sp2	1	
> 2004	123	123-10	Sp2	1	
> 2004	123	123-1	Sp3	0	
> 2004	123	123-2	Sp3	1	
> 2004	123	123-10	Sp3	0	
>
>
Hi agoijman,
You can do this using the rep_n_stack function.

adat<-data.frame(Year=rep(2004,3),Route=rep(123,3),
  Point=c("123-1","123-2","123-10"),Sp1=c(0,0,1),
  Sp2=c(1,1,1),Sp3=c(0,1,0))
library(prettyR)
rep_n_stack(adat,c("Sp1","Sp2","Sp3"),
  stack.names=c("Sp-names","Sp-values"))

Jim




More information about the R-help mailing list