我有一个包含多个向量的列表,我想按降序排序,并根据向量值获得一个排序的位置索引。
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
答案 0 :(得分:1)
如果你真的想要一个矢量列表(不同长度或其他),你可以使用 lapply 功能结合命令功能,如下面的代码:
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
希望有所帮助。