我有一份清单清单。我想根据参考矢量来订购。这与订购数据帧的question类似。但是我努力实现它。
我想根据“目标”向量中的顺序,通过“密钥”对下面的列表进行排序。
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)
)
答案 0 :(得分:1)
这是一种方法:
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
答案 1 :(得分:0)
下面的内容适用于我 - 逐行编写,用于说明目的
# 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)]