首页 > 解决方案 > 如何从 R 中的列表中返回 5 个最高值?

问题描述

我有一个来自for循环的值列表。我试图对它们进行排序并找到前 5 个值order(x,decreasing=TRUE)[1:5]。但它遇到了“'orderVector1'中未实现类型'list'”的问题。

所以我决定将列表转换为向量 by as.vector(unlist(x)),但它仍然告诉我列表错误orderVector1

我该怎么办?

x

1. 705.171526014177
2. 397.876803328549
3. 540.043448992021
4. 663.541433109646
5. 962.376210043159
6. 442.670573166487
7. 296.736087125474
8. 757.852870690724

as.vector(unlist(x))
705.171526014177 397.876803328549 540.043448992021 663.541433109646 962.376210043159 442.670573166487 296.736087125474 757.852870690724

order(x,decreasing=TRUE)[1:5]


Error in order(a, decreasing = TRUE): unimplemented type 'list' in 'orderVector1'

Traceback:

1. order(a, decreasing = TRUE)

标签: rlistsorting

解决方案


您可以从转换为dataframeortibble并使用:arrangedplyr

x <- list(c(1,2,3,4,5))

x <- tibble(nums = x)

new_x <- x %>%
  arrange(desc(nums))

head(new_x$nums, 5)


推荐阅读