Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何使用目标向量根据元素对列表进行排序?_R - Fatal编程技术网

R 如何使用目标向量根据元素对列表进行排序?

R 如何使用目标向量根据元素对列表进行排序?,r,R,我有一份清单。我想根据参考向量来排序。这与数据帧排序类似。然而,我努力实现它 我想根据“目标”向量中的顺序,按“键”对下面的列表进行排序 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 = lis

我有一份清单。我想根据参考向量来排序。这与数据帧排序类似。然而,我努力实现它

我想根据“目标”向量中的顺序,按“键”对下面的列表进行排序

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)
          )

target以下为我编写的作品-逐行编写,以便于说明

# 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)]
以下是一种方法:

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

我觉得没用。“Z”元素似乎丢失了。您需要
order
L[order(匹配(sappy(L,“[[”,“key”),target))
。添加顺序会起作用:
L[order(匹配(sappy(L,
[
,“key”),target)]
所以
匹配(sapply(L,
[
[
,“key”),target提供
3 2 1
,以及
匹配(sapply)(L,
[[
,“key”),target))
给出了
4 2 3 1
。这仅仅是一个(聪明的)“技巧”,以适当的“顺序”获得唯一索引吗