0

Say I have the data frame DF that I want to subset based on the data frame DF_select

library(dplyr)

set.seed(1)

DF <- data.frame(A = rep( LETTERS[1:4], each = 3),
             B = rep( c(1:3), 4),
             C = c("some", "thing"))

DF_select <- sample_n(DF, 5)

using row-indices won't work in the real example because the data frame DF has multiple rows for each matching row in DF_select.

filter with A %in% DF_select$A & B %in% ... won't work either as it will also match combinations that are not in the DF_select data.frame.

I can solve it by creating a temporary variable as unique row identifier in both data frames like this

mutate(DF, temp_var = paste(A,B,C, sep = "_"))

but I was wondering if there is a more elegant solution?

Latrunculia
  • 696
  • 1
  • 7
  • 15
  • I think this is already asked, check answers here http://stackoverflow.com/questions/37577087/look-up-from-different-dataframes-depending-on-a-column – user5249203 Jun 27 '16 at 19:16
  • 2
    I think you want `semi_join(DF, DF_select)` if I understand correctly (or `intersect(DF, DF_select)`) – talat Jun 27 '16 at 19:22
  • @docendo discimus `semi_join` it is. If you put it as an answer Ill be happy to accept it! – Latrunculia Jun 27 '16 at 19:53
  • @Latrunculia, I closed it as a duplicate of a canonical `merge` question. You find the answer [here](http://stackoverflow.com/a/21438584/3521006) – talat Jun 27 '16 at 19:56
  • @docendo discimus As you want. But my intention was to filter the data frame not to join it. That is why I didn't think about looking for a solution involving `*_join`. So although obvious when I think about it now, I would argue that it would be helpful having a question about subsetting / filtering that points to semi_join. In the end the great thing about SO is to have the answers to what people google not to what they should be googling. If you disagree, I won't insist though... – Latrunculia Jun 27 '16 at 20:04
  • Your question will stay here on SO. Anyone can find it and will then be able to look at the canonical question – talat Jun 27 '16 at 20:08

0 Answers0