gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:26:30 26 4
gpt4 key购买 nike

我的数据如下所示:

    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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com