R两个列表的比较

时间:2018-03-09 11:41:35

标签: r list

我想通过提取list1中列表2中项目的确切位置来比较两个列表。

a <- c(8, 28, 23, 21)
b <- c(28, 27, 8, 7)

我已尝试%in%或者相交,但我无法弄清楚如何获取共享项目的索引。

任何帮助都将不胜感激。

谢谢

1 个答案:

答案 0 :(得分:1)

您提到了一个列表,但已发布了两个整数向量。

作为%in%的更一般情况,您可以使用match。以下是基于一些示例数据的示例。

# Sample data
set.seed(2017);
lst <- list(
    one = sample(10),
    two = sample(10));
lst;
#$one
# [1] 10  5  4  3  9  8  1  2  6  7
#
#$two
# [1]  7  1  9  4  3  2  5  6 10  8

# Index of lst$one elements in lst$two. 
idx_one_in_two <- match(lst[[1]], lst[[2]]);
idx_one_in_two;
# [1]  9  7  4  5  3 10  2  6  8  1

例如,lst$onelst$one[1] = 7)中的元素1位于9中的lst$two位置。

同样,对于lst$two中的元素lst$one

# Index of lst$two elements in lst$one. 
idx_two_in_one <- match(lst[[2]], lst[[1]]);
# [1] 10  7  5  3  4  8  2  9  1  6

更新

根据您的示例数据,您可以执行以下操作:

a <- c(8, 28, 23, 21)
b <- c(28, 27, 8, 7)

# Index of a in b
match(a, b);
#[1]  3  1 NA NA

# Index of b in a
match(b, a);
#[1]  2 NA  1 NA
相关问题