[R] Does split() preserve order?

Bert Gunter gunter.berton at gene.com
Thu Aug 27 01:50:21 CEST 2009

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])
[1] 3

[1] 2

[1] 1

> f <- factor(letters[3:1],levels = letters[3:1])
> split(1:3,f)
[1] 1

[1] 2

[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)) {

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
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