In a list object ordering characters in each row

Viewed 48

I have a list object. I used strsplit(data, ";") to unlist. It is characters "A";"B" so on and each row has different length. Therefore, I wrote a for loop to create a matrix. I want to have column 1 all same object "A".

Here is the code I wrote but it does not work as I wanted.

myList <- list()
myList[[1]] <- c("A", "C", 0, 0)
myList[[2]] <- c("A", "B", "C")
myList[[3]] <- c("A", 0, 0, 0, 0)
myList[[4]] <- c("B", "A")
myList[[5]] <- c("Aa", "A", "B", 0, 0)
myList[[6]] <- c("Aa", "A", "C", 0, 0)
myList[[7]] <- c("C", "A", 0, 0)

myList

TD=TD2=matrix(0,length(myList),5)
for(i in 1:length(myList))
{
  m1=length(myList[[i]])
  TD[i,1:m1]=matrix( myList[[i]] , ncol = m1 , byrow = TRUE )
}

for(j in 1:length(myList)){
  TD2[j,]=TD[j,order(TD[j,],decreasing = T)]
}

Desired output to be

     [,1] [,2] [,3] [,4] [,5]
[1,] "A"  "C"  "0"  "0"  "0" 
[2,] "A"  "C"  "B"  "0"  "0" 
[3,] "A"  "0"  "0"  "0"  "0" 
[4,] "A"  "B"  "0"  "0"  "0" 
[5,] "A"  "B" "Aa"  "0"  "0" 
[6,] "A"  "C" "Aa"  "0"  "0" 
[7,] "A"  "C"  "0"  "0"  "0" 
2 Answers

You can define a factor object with custom order with factor(..., ordered = T) and sort it.

ord <- names(sort(table(unlist(myList))[-1], dec = T))
len <- max(lengths(myList))

t(sapply(myList, function(x){
  y <- sort(factor(x, levels = c(ord, "0"), ordered = T))[1:len]
  replace(y, is.na(y), "0")
}))

#      [,1] [,2] [,3] [,4] [,5]
# [1,] "A"  "C"  "0"  "0"  "0" 
# [2,] "A"  "C"  "B"  "0"  "0" 
# [3,] "A"  "0"  "0"  "0"  "0" 
# [4,] "A"  "B"  "0"  "0"  "0" 
# [5,] "A"  "B"  "Aa" "0"  "0" 
# [6,] "A"  "C"  "Aa" "0"  "0" 
# [7,] "A"  "C"  "0"  "0"  "0"

Not exactly what you want, but since you can create a frequency table, this should also work:

TD = matrix(0,length(myList),5)
for (i in 1:length(myList)) {
    myList[[i]] = sort(myList[[i]][which(myList[[i]] != "0")])
    for (j in 1:length(myList[[i]])) TD[i, j] = myList[[i]][j]
}

> TD
     [,1] [,2] [,3] [,4] [,5]
[1,] "A"  "C"  "0"  "0"  "0" 
[2,] "A"  "B"  "C"  "0"  "0" 
[3,] "A"  "0"  "0"  "0"  "0" 
[4,] "A"  "B"  "0"  "0"  "0" 
[5,] "A"  "Aa" "B"  "0"  "0" 
[6,] "A"  "Aa" "C"  "0"  "0" 
[7,] "A"  "C"  "0"  "0"  "0" 
Related