0

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

2
  • 1
    What would be the desired output from your example data? Commented Mar 25, 2016 at 18:16
  • Unless those letters are objects, they need to be quoted, and you should probably also give the variables names so they don't end up gross. Also, you're looking for the [data.frame] tag, not [dataframes]. Commented Mar 25, 2016 at 18:28

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

which(d2 == value)) is exactly what I was looking for. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.