David Z
David Z

Reputation: 7041

How to order all list elements by a vector in R?

Suppose I have a string vector:

 vc<-c("a", "c", "b")

and a list:

ls<-list(x<-cbind(v1=c(1, 2, 3), v2=c("a", "b","c")),
         y<-cbind(v1=c(7, 8, 0), v2=c("c", "a","b")),
         z<-cbind(v1=c(5, 6, 9), v2=c("c", "b","a")))

My question is how to order all elements in ls using column v2 by the order of vc?

Upvotes: 2

Views: 212

Answers (1)

akrun
akrun

Reputation: 887148

You can use match to match the values in the 2nd column with the vector. As it is a list, lapply can be used

 lapply(ls, function(x) x[match(vc,x[,2]),])

Upvotes: 2

Related Questions