Reputation: 355
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
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