r - 在 R 中排序未正确排序数字

标签 r sorting

我的数据如下所示:

    score        temp
1 a.score  0.05502011
2 b.score  0.02484594
3 c.score -0.07183767
4 d.score -0.06932274
5 e.score -0.15512460

我想根据从最负到最正的值对相同内容进行排序,取前 4 个。我尝试:

> topfour.values <- apply(temp.df, 2, function(xx)head(sort(xx), 4, na.rm = TRUE, decreasing = FALSE))
> topfour.names  <- apply(temp.df, 2, function(xx)head(names(sort(xx)), 4, na.rm = TRUE))
> topfour        <- rbind(topfour.names, topfour.values)

我明白了

> topfour.values
                        temp[, 1]                           
    d.score              "-0.06932274"            
    c.score              "-0.0718376680"          
    e.score              "-0.1551246"             
    b.score              " 0.02484594"   

这是什么顺序?我做错了什么以及如何正确排序?

我尝试过 method == "Quick"和 method == "Shell"作为选项,但顺序仍然没有意义。

最佳答案

我相信您获取的数据类型错误。了解如何将数据导入 R 会很有用。在上面的示例中,您处理的是字符向量而不是数字向量。

head(with(df, df[order(temp), ]), 4)
    score        temp
5 e.score -0.15512460
3 c.score -0.07183767
4 d.score -0.06932274
2 b.score  0.02484594

采用 Greg Snow 提出的方法,并考虑到您只对最高值的向量感兴趣,并且在这种情况下不可能使用 partial 参数,对比较 order 和 sorl.list 表明,即使对于 1e7 大小的向量,差异也可能无关紧要。

df1 <- data.frame(temp = rnorm(1e+7),
                  score = sample(letters, 1e+7, rep = T))

library(microbenchmark)
microbenchmark(
  head(with(df1, df1[order(temp), 1]), 4),
  head(with(df1, df1[sort.list(temp), 1]), 4),
  head(df1[order(df1$temp), 1], 4),
  head(df1[sort.list(df1$temp), 1], 4),
  times = 1L
  )

Unit: seconds
                                        expr      min       lq   median       uq      max neval
     head(with(df1, df1[order(temp), 1]), 4) 13.42581 13.42581 13.42581 13.42581 13.42581     1
 head(with(df1, df1[sort.list(temp), 1]), 4) 13.80256 13.80256 13.80256 13.80256 13.80256     1
            head(df1[order(df1$temp), 1], 4) 13.88580 13.88580 13.88580 13.88580 13.88580     1
        head(df1[sort.list(df1$temp), 1], 4) 13.13579 13.13579 13.13579 13.13579 13.13579     1

关于r - 在 R 中排序未正确排序数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24002946/

相关文章:

r - 有没有办法命名列表的所有元素

r - 冒号运算符的异常行为 : in R

r - 许多列中的 str_replace 问题以及

R:如何从早到晚对每天的每小时测量进行排序,并根据此顺序添加一个数字?

c# - 根据字符串位置对字符串数组进行排序 (C#)

mysql - 舍入时间戳列以使其涵盖更大的时间段

r - 有没有办法在 R Shiny 应用程序中创建的对象上运行任意代码?

r - 比较多个范围的整体重叠

node.js - 使用限制和排序时MongoDB解析错误

python - 为什么平分比排序慢