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

David L Carlson dcarlson at tamu.edu
Sun Oct 7 05:24:51 CEST 2012


Also reshape() will work:

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))
reshape(adat, varying=4:6, v.name="Sp-value", 
  times=c("Sp1", "Sp2", "Sp3"), idvar="Point", 
  timevar="Sp-name", direction="long")

----------------------------------------------
David L Carlson
Associate Professor of Anthropology
Texas A&M University
College Station, TX 77843-4352


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Jim Lemon
> Sent: Saturday, October 06, 2012 7:36 PM
> To: agoijman
> Cc: r-help at r-project.org
> Subject: Re: [R] Presence/ absence data from matrix to single column
> 
> 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
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-
> guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list