[R] Base within reverses column order

Duncan Murdoch murdoch.duncan at gmail.com
Fri Apr 4 19:55:22 CEST 2014


On 04/04/2014 1:32 PM, Dan Murphy wrote:
> I just noticed this annoyance, but I'm not the first one, apparently
> -- see http://lists.r-forge.r-project.org/pipermail/datatable-help/2012-May/001176.html
>
> The thread never answered the OP's question "Is this a bug?" so I
> assume the answer, unfortunately, is No.
>
> If not a bug, do users of within have a workaround to produce a result
> with columns as ordered within 'within'? I can think of a way using
> names and subset-with-select, but that seems unduly kludgy.

I wouldn't be surprised if it is not consistent about that.  It uses 
as.list to convert an environment to a list, and that's where the 
reversal occurs:  but since environments are unordered collections of 
objects, you just happen to be seeing an undocumented and unpromised 
property of the internal implementation.

If the order matters to you, then create your initial dataframe with the 
new variables (set to NA, for example), or reorder it afterwards.  But 
generally speaking even in a dataframe (which is an ordered collection 
of objects), it's better to program in a way that doesn't make 
assumptions about the order.  Columns have names, and you should use those.

Duncan Murdoch




More information about the R-help mailing list