我有一个 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

关于r - r 中的 Order() 函数排序不正确,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29399518/

10-11 04:04
查看更多