If x is a vector (or data frame) that is in a particular order, and I call split(x, f) to partition x, will the elements of each partition remain in order? That is, is the following assertion always TRUE? for(i in split(x, f)) { stopifnot(!is.unsorted(i)) } I suspect that this is the case, but the help page does not discuss preservation of order in the result of split().
Well, it depends on what you mean by "order". Split() (and most other R functions that group things by factor levels, to my knowledge) use the ordering of the factor levels -- which you can control via ordered(), for example -- but which is by default lexicographic, which may or may not be what you want. Viz.> split(1:3,letters[3:1])$a [1] 3 $b [1] 2 $c [1] 1> f <- factor(letters[3:1],levels = letters[3:1]) > split(1:3,f)$c [1] 1 $b [1] 2 $a [1] 3 Bert Gunter Genentech Nonclinical Biostatisics -----Original Message----- From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Alistair Gee Sent: Wednesday, August 26, 2009 4:41 PM To: r-help at r-project.org Subject: [R] Does split() preserve order? If x is a vector (or data frame) that is in a particular order, and I call split(x, f) to partition x, will the elements of each partition remain in order? That is, is the following assertion always TRUE? for(i in split(x, f)) { stopifnot(!is.unsorted(i)) } I suspect that this is the case, but the help page does not discuss preservation of order in the result of split(). ______________________________________________ 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.
On Wed, 26 Aug 2009, Alistair Gee wrote:> If x is a vector (or data frame) that is in a particular order, and I > call split(x, f) to partition x, will the elements of each partition > remain in order?They must for example( split ) to work as advertised, viz. ### Calculate z-scores by group z <- unsplit(lapply(split(x, g), scale), g) HTH, Chuck> > That is, is the following assertion always TRUE? > > for(i in split(x, f)) { > stopifnot(!is.unsorted(i)) > } > > I suspect that this is the case, but the help page does not discuss > preservation of order in the result of split(). > > ______________________________________________ > 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. >Charles C. Berry (858) 534-2098 Dept of Family/Preventive Medicine E mailto:cberry at tajo.ucsd.edu UC San Diego http://famprevmed.ucsd.edu/faculty/cberry/ La Jolla, San Diego 92093-0901