简体   繁体   中英

sorted descending index of positions based on the vector values in a list

I have a list that consists on multiple vectors which I would like to sort in descending order and obtain a sorted index of positions based on the vector values.

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.

Would you happen to know if there is a way to sort in descending order a list of vectors and obtain a sorted index based on the vector values as to obtain something like.

4,2,3,1

If you really want to have a list of vectors (of different lengths or whatever), you can use the lapply function combined with the order function, like code below:

    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)

For the "x" list containing the following values:

[[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

... it gives you a list of ordered indexes for each vector in a new list of the same length, which looks something like this.

[[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

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM