C. DAVID
C. DAVID

Reputation: 61

R comparison of two lists

I have two lists that I want to compare by extracting the exact positions of items in list1 that are also in list 2.

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

I have tried %in% or intersect but I can't figure out how to get the index of shared items.

Any help would be appreciated.

Thank you

Upvotes: 1

Views: 3682

Answers (1)

Maurits Evers
Maurits Evers

Reputation: 50668

You mentioned a list, but have posted two integer vectors.

As a more general case to %in% you can use match. Here is an example based on some sample data.

# 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

For example, element 1 in lst$one (lst$one[1] = 7) is located at position 9 in lst$two.

Similarly, for elements lst$two in 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

Update

Based on your sample data, you can do the following:

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

Upvotes: 2

Related Questions