【问题标题】:sorted descending index of positions based on the vector values in a list根据列表中的向量值排序的位置降序索引
【发布时间】:2025-12-17 21:30:02
【问题描述】:

我有一个包含多个向量的列表,我想按降序排序并根据向量值获得位置的排序索引。

a <- c(1)
b <- c(9)
c <- c(6)
d <- c(11)

w <- list(a,b,c,d)

# if I do 

sort(w)
Error in sort.int(x, na.last = na.last, decreasing = decreasing, ...) : 
'x' must be atomic

# so I convert into a matrix
as.matrix(w)
     [,1]
[1,] 1   
[2,] 9   
[3,] 6   
[4,] 11  

however when I do sort on the matrix does not work but it does on a data 
frame 

sort(as.matrix(w))
Error in sort.int(x, na.last = na.last, decreasing = decreasing, ...) : 
'x' must be atomic

sort(as.data.frame(w))
   X1 X6 X9 X11
1  1  6  9  11

sort(which(as.matrix(w)))
Error in sort(which(as.matrix(w))) : 
error in evaluating the argument 'x' in selecting a method for function   
'sort': Error in which(as.matrix(w)) : argument to 'which' is not logical

which(sort(as.matrix(w)))
Error in sort.int(x, na.last = na.last, decreasing = decreasing, ...) : 
'x' must be atomic.

您是否碰巧知道是否有一种方法可以对向量列表进行降序排序,并根据向量值获得排序索引以获得类似的结果。

4,2,3,1

【问题讨论】:

  • order(unlist(w),decreasing=TRUE) 获取索引。使用该索引对列表进行排序。 w[order(unlist(w),decreasing=TRUE)]
  • 为什么是list?只需将w&lt;-c(a,b,c,d) 定义为向量而不是列表。然后,您可以直接在w 上应用sortorder
  • 谢谢 Nicola 是一个列表,因为我得到了一个包含 700 个向量的输出列表,这是一个示例

标签: r


【解决方案1】:

如果您真的想要一个向量列表(不同长度或其他),您可以将 lapply 函数与 order 函数结合使用,如下面的代码:

    a <- c(runif(5,0,2))
    b <- c(runif(7,0,2))
    c <- c(runif(9,0,2))
    d <- c(runif(11,0,2))

    x <- list(a,b,c,d)

    lapply(x,order, decreasing = T)

对于包含以下值的“x”列表:

[[1]] [1] 1.0223396 0.4150902 0.4573163

[[2]] [1] 1.19142399 1.14974440 0.15412876 0.07108116 1.28559098

[[3]] [1] 1.857230 1.196185 1.121801 1.052055 1.970190 1.015284
1.365576

[[4]] [1] 1.2030824 0.4777374 0.5163319 1.4586192

...它为您提供了一个相同长度的新列表中每个向量的有序索引列表,看起来像这样。

[[1]]
[1] 2 3 1

[[2]]
[1] 4 3 2 1 5

[[3]]
[1] 6 4 3 2 7 1 5

[[4]]
[1] 2 3 1 4

希望对您有所帮助。

【讨论】: