Domanda

I have two easy matrices (or df's) to merge:

a <- cbind(one=0:15, two=0:15, three=0:15)
b <- cbind(one=0:15, two=0:15, three=0:15)
#a <- data.frame(one=0:15, two=0:15, three=0:15)
#b <- data.frame(one=0:15, two=0:15, three=0:15)


No problem: after sorting on column one, column one is output ascending nicely from 0 to 15:

merge(a,b,by=c("one"), sort=T)
   one two.x three.x two.y three.y
1    0     0       0     0       0
2    1     1       1     1       1
3    2     2       2     2       2
4    3     3       3     3       3
5    4     4       4     4       4
6    5     5       5     5       5
7    6     6       6     6       6
8    7     7       7     7       7
9    8     8       8     8       8
10   9     9       9     9       9
11  10    10      10    10      10
12  11    11      11    11      11
13  12    12      12    12      12
14  13    13      13    13      13
15  14    14      14    14      14
16  15    15      15    15      15


But wait: when merging on two columns --- both numeric --- the sort order suddenly seems alphabetic.

merge(a,b,by=c("one", "two"), sort=T)
   one two three.x three.y
1    0   0       0       0
2    1   1       1       1
3   10  10      10      10
4   11  11      11      11
5   12  12      12      12
6   13  13      13      13
7   14  14      14      14
8   15  15      15      15
9    2   2       2       2
10   3   3       3       3
11   4   4       4       4
12   5   5       5       5
13   6   6       6       6
14   7   7       7       7
15   8   8       8       8
16   9   9       9       9

Eww, gross. What's going on? And what do I do?

È stato utile?

Soluzione

Based on @joran's comments, it looks like if you want the rows to be sorted in any particular order, you should explicitly set it yourself.

If the order you'd like is one in which the rows have increasing values of one or more columns, you can use the function order(), like this:

X <- merge(a, b, by = c("one", "two"))
X[with(X, order(one, two)),]
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top