3

I have a list of lists. I want to order this according to a reference vector. This is similar to this question on ordering dataframes. However I struggled to implement it.

I want to sort this list below by its 'key' according to the order in the 'target' vector.

target <- c("c", "b", "a")
L <- list(
          X = list(key = "a", val = 6),
          Y = list(key = "b", val = 5),
          Y = list(key = "b", val = 0),
          Z = list(key = "c", val = 4)
          )
Community
  • 1
  • 1
drstevok
  • 715
  • 1
  • 6
  • 15

2 Answers2

1

Here is one approach:

L[order(vapply(L, 
               function(x, target) which(x$key == target), 
               target = target, 
               FUN.VALUE = 1L)
        )
 ]
#$Z
#$Z$key
#[1] "c"
#
#$Z$val
#[1] 4
#
#
#$Y
#$Y$key
#[1] "b"
#
#$Y$val
#[1] 5
#
#
#$Y
#$Y$key
#[1] "b"
#
#$Y$val
#[1] 0
#
#
#$X
#$X$key
#[1] "a"
#
#$X$val
#[1] 6
Roland
  • 127,288
  • 10
  • 191
  • 288
0

The following works for me - written line by line for expository purposes

# Get keys from the original list
sapply(L, `[[`, "key")
# Use match to order these
match(sapply(L, `[[`, "key"), target)
# Now select those items from the original list using the reference from match
L[match(sapply(L, `[[`, "key"), target)]
drstevok
  • 715
  • 1
  • 6
  • 15