如何获得k个最小的元素?

时间:2022-02-06 13:38:17

Assume I have the vector c(3,7,1,9,7,6,4) and I need to get its three least elements c(3,1,4). How can I do it with R?

假设我有矢量c(3,7,1,9,7,6,4),我需要得到它的三个最小元素c(3,1,4)。我怎么能用R做呢?

2 个解决方案

#1


2  

One possible solution:

一种可能的方案:

sort( c(3,7,1,9,7,6,4) )[1:3]

#2


2  

Another possible solution:

另一种可能的方案

sort(x = c(3,7,1,9,7,6,4), partial = 3)[1:3]

Which performs a partial sort.

哪个执行局部排序。

#1


2  

One possible solution:

一种可能的方案:

sort( c(3,7,1,9,7,6,4) )[1:3]

#2


2  

Another possible solution:

另一种可能的方案

sort(x = c(3,7,1,9,7,6,4), partial = 3)[1:3]

Which performs a partial sort.

哪个执行局部排序。