Reordering factor gives different results, depending on which packages are loaded
Solution 1:
This happens because:
-
gmodels
importsgdata
-
gdata
creates a new method forreorder.factor
Start a clean session. Then:
methods("reorder")
[1] reorder.default* reorder.dendrogram*
Now load gdata
(or load gmodels
, which has the same effect):
library(gdata)
methods("reorder")
[1] reorder.default* reorder.dendrogram* reorder.factor
Notice there is no masking, since reorder.factor
doesn't exist in base
Recreate the problem, but this time explicitly call the different packages:
group = c("C","F","D","B","A","E")
num = c(12,11,7,7,2,1)
data = data.frame(group,num)
The base R version (using reorder.default
):
str(transform(data, group=stats:::reorder.default(group,-num)))
'data.frame': 6 obs. of 2 variables:
$ group: Factor w/ 6 levels "C","F","B","D",..: 1 2 4 3 5 6
..- attr(*, "scores")= num [1:6(1d)] -2 -7 -12 -7 -1 -11
.. ..- attr(*, "dimnames")=List of 1
.. .. ..$ : chr "A" "B" "C" "D" ...
$ num : num 12 11 7 7 2 1
The gdata
version (using reorder.factor
):
str(transform(data, group=gdata:::reorder.factor(group,-num)))
'data.frame': 6 obs. of 2 variables:
$ group: Factor w/ 6 levels "A","B","C","D",..: 3 6 4 2 1 5
$ num : num 12 11 7 7 2 1