Michael Denslow
2011-May-18 13:37 UTC
[R] matrix help (first occurrence of variable in column)
Dear R help, Apologies for the less than informative subject line. I will do my best to describe my problem. Consider the following matrix: mdat <- matrix(c(1,0,1,1,1,0), nrow = 2, ncol=3, byrow=TRUE, dimnames = list(c("T1", "T2"), c("sp.1", "sp.2", "sp.3"))) mdat In my actual data I have time (rows) and species occurrences (0/1 values, columns). I want to count the number of new species that occur at a given time sample. For the matrix above the answer would be 1. Is there a simple way to figure out if the species has never occurred before and then sum them up? Thanks in advance, Micheal -- Michael Denslow I.W. Carpenter Jr. Herbarium [BOON] Department of Biology Appalachian State University Boone, North Carolina U.S.A. -- AND -- Communications Manager Southeast Regional Network of Expertise and Collections sernec.org 36.214177, -81.681480 +/- 3103 meters
jim holtman
2011-May-19 01:49 UTC
[R] matrix help (first occurrence of variable in column)
Is this what you were after:> mdat <- matrix(c(1,0,1,1,1,0), nrow = 2, ncol=3, byrow=TRUE,+ dimnames = list(c("T1", "T2"), + c("sp.1", "sp.2", "sp.3")))> > mdatsp.1 sp.2 sp.3 T1 1 0 1 T2 1 1 0> # do 'rle' on each column and see if it is length >1 and starts with zero > mdat.df <- as.data.frame(mdat) > new.spec <- sapply(mdat.df, function(x){+ x.rle <- rle(x) + (length(x.rle$values) > 1) & (x.rle$values[1L] == 0) + })> names(mdat.df)[new.spec][1] "sp.2">On Wed, May 18, 2011 at 9:37 AM, Michael Denslow <michael.denslow at gmail.com> wrote:> Dear R help, > Apologies for the less than informative subject line. I will do my > best to describe my problem. > > Consider the following matrix: > > mdat <- matrix(c(1,0,1,1,1,0), nrow = 2, ncol=3, byrow=TRUE, > ? ? ? ? ? ? ? dimnames = list(c("T1", "T2"), > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? c("sp.1", "sp.2", "sp.3"))) > > mdat > > In my actual data I have time (rows) and species occurrences (0/1 > values, columns). I want to count the number of new species that occur > at a given time sample. For the matrix above the answer would be 1. > > Is there a simple way to figure out if the species has never occurred > before and then sum them up? > > Thanks in advance, > Micheal > > -- > Michael Denslow > > I.W. Carpenter Jr. Herbarium [BOON] > Department of Biology > Appalachian State University > Boone, North Carolina U.S.A. > -- AND -- > Communications Manager > Southeast Regional Network of Expertise and Collections > sernec.org > > 36.214177, -81.681480 +/- 3103 meters > > ______________________________________________ > 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. >-- Jim Holtman Data Munger Guru What is the problem that you are trying to solve?