0
votes

Let's say I have a list in R:

MyList <- list(A = rnorm(5), B = seq(10), C = letters)

Now let's say I also have a vector that matches the names of MyList but has them in a different sequence:

pattern <- c("B", "A", "C")

How can I sort MyList to match the order in pattern? The result should look like this, but with the original names still assigned.

NewList <- list(MyList[["B"]], MyList[["A"]], MyList[["C"]])

This seems straightforward if pattern has a natural order (e.g., ascending or descending). But what if it doesn't, so I can't use sort or order?

My ideal solution would only use base R.

1
Are you looking for this sapply(pattern, function(x) MyList[[x]]).Chirayu Chamoli
Just use name subsetting: MyList[pattern] or MyList.reordered <- MyList[pattern] for assignment.lmo
@imo Thats way better.Chirayu Chamoli
@lmo, got it, thank you.ulfelder

1 Answers

1
votes

It might help to take a look at ?"[". Specifically, the difference between [[ and [ confused me for a while. Here, the key thing to note is that you can use [ to subset to multiple elements, while [[ can only be used for one element.

So as @lmo points out, what you want to do here is MyList[pattern]. In case you didn't realize, this can work because names(MyList) matches up with the elements in pattern -- you can index/ subset not only by numerical index (e.g., 1:3), but also by name (e.g., c("A","B","C")).

TLDR:

NewList <- MyList[pattern]