r中的Order()函数排序不正确



我有一个数字的df,正在进行一些排序。输出将7放在70旁边,就好像7是70一样。为什么会发生这种情况。下面粘贴的东西是实际输出。注意263是如何被处理为小于27的,就好像在27中的7后面有一个0一样。4在38之后,就好像4表示40一样。我正在使用order()。

 feat_1  25
 feat_10  26
 feat_24 263
 feat_48  27
 feat_55  27
 feat_75  36
 feat_16  37
 feat_53  38
 feat_89  38
 feat_28   4

之所以会发生这种情况,是因为您对字符而不是数字进行排序。这是一个常见的问题,尽管不是一个明显的问题。对于初学者来说,使用orderdata.frame进行排序很容易,这就是我将在测试用例中演示解决方案的方法。

你应该试试这个:

col1 <- c('a', 'b', 'c')
col2 <- c("25", "42" ,"4")
df <- data.frame(col1, col2)
## This is the wrong approach:
df[order(df$col2),]
col1 col2
1   a   25
3   c    4
2   b   42
## This is the right approach, conver the second vector to numeric vector:
df$col2 <- as.numeric(as.character(df$col2))
df[order(df$col2),]
  col1 col2
3   c    4
1   a   25
2   b   42

您也可以使用gtools包中的mixedsortmixedorder(用于快速替换),并且不需要将列转换为数字,因为它处理字符数或字母数字字符串:

数据

df <- read.table(text='feat_1  25
 feat_10  "26"
 feat_24  "263"
 feat_48  "27"
 feat_55  "27"
 feat_75  "36"
 feat_16  "37"
 feat_53  "38"
 feat_89  "38"
 feat_28   "4"')

解决方案

library(gtools)
#you use mixedorder in exactly the same way as base order
> df[mixedorder(df$V2),]
        V1  V2
10 feat_28   4
1   feat_1  25
2  feat_10  26
4  feat_48  27
5  feat_55  27
6  feat_75  36
7  feat_16  37
8  feat_53  38
9  feat_89  38
3  feat_24 263

最新更新