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.
sapply(pattern, function(x) MyList[[x]])
. – Chirayu ChamoliMyList[pattern]
orMyList.reordered <- MyList[pattern]
for assignment. – lmo