chippycentra
chippycentra

Reputation: 3432

Sort matrix colnames to match element order in a list

I have a particular list such as:

my_list<-list("Cluster18904", "Cluster6294", "Cluster17424", "Cluster26257", 
     "Cluster27053", "Cluster2905", "Cluster16096", "Cluster14552")

which looks like:

my_list

[[1]]
[1] "Cluster18904"

[[2]]
[1] "Cluster6294"

[[3]]
[1] "Cluster17424"

[[4]]
[1] "Cluster26257"

[[5]]
[1] "Cluster27053"

[[6]]
[1] "Cluster2905"

[[7]]
[1] "Cluster16096"

[[8]]
[1] "Cluster14552"

and I have a matrix with the same colnames but I'm looking for a solution in order to order the column of the matrix to match the same order as in my_list

I tried:

as.data.frame(matrix)[,my_list]

But I get :

Error in .subset(x, j) : 'list' incorrect index type

Upvotes: 1

Views: 476

Answers (3)

user16051136
user16051136

Reputation:

This will sort the column names according to the list names, by first converting the list names to a vector of strings.

matrix[,match(colnames(matrix),as.character(my_list))]

Upvotes: 2

ThomasIsCoding
ThomasIsCoding

Reputation: 102900

Another base R option

as.data.frame(matrix)[simplify2array(my_list)]

Upvotes: 1

akrun
akrun

Reputation: 887971

We need to unlist

as.data.frame(matrix)[, unlist(my_list)]

if there are column names not matching, then use intersect

dat1 <- as.data.frame(matrix)
nm1 <- intersect(names(dat1), unlist(my_list))
dat1[nm1]

Upvotes: 1

Related Questions