Home > Blockchain >  Sapply list output with 2 columns, how to arrange in ascending order?
Sapply list output with 2 columns, how to arrange in ascending order?

Time:09-08

trueFalseACT always have 4 colums, but can have 1 or 10 rows

      trueFalseACT <- structure(c(TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, 
FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), dim = c(4L, 
4L))



[,1]  [,2]  [,3]  [,4]
[1,]  TRUE FALSE FALSE FALSE
[2,] FALSE FALSE  TRUE FALSE
[3,] FALSE  TRUE FALSE FALSE
[4,] FALSE FALSE FALSE FALSE

>  str(trueFalseACT)
List of 28
     $ : logi [1:3, 1:4] TRUE TRUE FALSE FALSE FALSE FALSE ...
     $ : logi [1:4, 1:4] TRUE FALSE FALSE FALSE FALSE FALSE ...
     $ : logi [1:4, 1:4] FALSE TRUE FALSE FALSE FALSE FALSE ...
     $ : logi [1:4, 1:4] TRUE FALSE FALSE FALSE FALSE FALSE ...
     $ : logi [1:5, 1:4] TRUE FALSE FALSE TRUE FALSE FALSE ...

> class(trueFalseACT)
[1] "list"

list_sapply will always have 2 columns, row and col. dput to replicate:

 list_sapply <-  list(structure(c(1L, 2L, 1L, 1L), dim = c(2L, 2L), dimnames = list(
        NULL, c("row", "col"))), structure(c(1L, 3L, 2L, 1L, 2L, 
    3L), dim = 3:2, dimnames = list(NULL, c("row", "col"))), structure(c(2L, 
    3L, 1L, 1L, 3L, 4L), dim = 3:2, dimnames = list(NULL, c("row", 
    "col"))), structure(c(1L, 3L, 2L, 1L, 2L, 3L), dim = 3:2, dimnames = list(
        NULL, c("row", "col"))), structure(c(1L, 4L, 2L, 3L, 1L, 
    1L, 4L, 4L), dim = c(4L, 2L), dimnames = list(NULL, c("row", 
    "col"))))



  list_sapply <- sapply(trueFalseACT,which,T)
list_sapply[2]
[[1]]
     row col
[1,]   1   1
[2,]   3   2
[3,]   2   3

I want that the rows in order 1,2,3 on list_sapply ...

CodePudding user response:

This should work despite the number of rows and cols. However, I did not use sapply but a for loop.

row <- c()
col <- c()
for(i in 1:nrow(trueFalseACT)){
  for(j in 1:ncol(trueFalseACT)){
    if(trueFalseACT[i, j] == TRUE){
      row <- c(row, i)
      col <- c(col, j)
    }
  }
}
cbind(row, col)

Since the iteration is first on the rows, it will always return the rows ordered

     row col
[1,]   1   1
[2,]   2   3
[3,]   3   2

CodePudding user response:

To put each matrix in list_apply in order, you can use lapply and order:

lapply(list_sapply, \(x) x[order(x[, 1]), ])

Output

[[1]]
     row col
[1,]   1   1
[2,]   2   1

[[2]]
     row col
[1,]   1   1
[2,]   2   3
[3,]   3   2

[[3]]
     row col
[1,]   1   4
[2,]   2   1
[3,]   3   3

[[4]]
     row col
[1,]   1   1
[2,]   2   3
[3,]   3   2

[[5]]
     row col
[1,]   1   1
[2,]   2   4
[3,]   3   4
[4,]   4   1

To get the indices on trueFalseACT and put in order, you can use a combination of which and order:

out <- which(trueFalseACT, arr.ind = TRUE)
out[order(out[, 1]), ]

Output

     row col
[1,]   1   1
[2,]   2   3
[3,]   3   2
  •  Tags:  
  • r
  • Related