【发布时间】: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<-c(a,b,c,d)定义为向量而不是列表。然后,您可以直接在w上应用sort和order。 -
谢谢 Nicola 是一个列表,因为我得到了一个包含 700 个向量的输出列表,这是一个示例
标签: r