如何在R中获得其索引的前n个值?

xir*_*uru 2 r

我有一个只有一列的数据框,我想用它的索引找到最大的三个值.例如,我的数据框架df如下所示:

  distance
1 1
2 4
3 2
4 3
5 4
6 5
7 5
Run Code Online (Sandbox Code Playgroud)

我想找到其索引最大的3值,所以我的预期结果是:

  distance    
6 5
7 5
2 4
5 4
4 3
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?由于我只有一列,是否也可以使用列表而不是数据帧?

akr*_*run 6

我们可以使用sortwith index.return=TRUE来返回带有索引的值list.然后我们可以list基于'x'中的前3个唯一元素对子集进行子集化.

lst <- sort(df1$distance, index.return=TRUE, decreasing=TRUE)
lapply(lst, `[`, lst$x %in% head(unique(lst$x),3))
#$x
#[1] 5 5 4 4 3

#$ix
#[1] 6 7 2 5 4
Run Code Online (Sandbox Code Playgroud)