h7681
h7681

Reputation: 355

R - Match a value from one data frame with multiple values from another

For example, say I have the two data frames...

d1 <- data.frame(c(a,b,c,d,e,f))
d2 <- data.frame(c(a,a,a,b,b,d,d,d,d,d,e,e,f))

And I want to search 'a' from d1 in d2 and reveal the index of every matching value, which can be stored in a vector.

I've searched for and played around with the Match() function, but this only seems to work when there is just one matching value.

Thanks

Upvotes: 0

Views: 1341

Answers (1)

cderv
cderv

Reputation: 6542

To match a value from one data frame with multiple values from another, you could loop through the first data.frame and get the indice in the second for each value.

d1 <- data.frame(x = c("a","b","c","d","e","f"), stringsAsFactors = F)
d2 <- data.frame(x = c("a","a","a","b","b","d","d","d","d","d","e","e","f"), stringsAsFactors = F)

sapply(d1$x, function(value) which(d2 == value))
#> $a
#> [1] 1 2 3
#> 
#> $b
#> [1] 4 5
#> 
#> $c
#> integer(0)
#> 
#> $d
#> [1]  6  7  8  9 10
#> 
#> $e
#> [1] 11 12
#> 
#> $f
#> [1] 13

Upvotes: 1

Related Questions