Question: I have two data frames. df\_sub is a subset of the main data frame, df. I want to take a subset of df based on df\_sub where the resulting data frame is going to be df\_sub plus the observations that occur before and after.

As an example, consider the two data sets

```
df <- data.frame(var1 = c("a", "x", "x", "y", "z", "t"),
                    var2 = c(4, 1, 2, 45, 56, 89))

df_sub <- data.frame(var1 = c("x", "y"),
                       var2 = c(2, 45))

```

They look like

```
> df
  var1 var2
1    a    4
2    x    1
3    x    2
4    y   45
5    z   56
6    t   89

> df_sub
  var1 var2
1    x    2
2    y   45

```

The result I want would be

```
> df_result
2    x    1
3    x    2
4    y   45
5    z   56

```

I was thinking of using an inner\_join or something similar

Answer: 
We could use `match` to get the index, then add or subtract 1 on those index, take the `unique` and subset the rows

```
v1 <- na.omit(match(do.call(paste, df_sub), do.call(paste, df)) )
df[unique(v1 + rep(c(-1, 0, 1), each = length(v1))),]

```

-output

```
  var1 var2
2    x    1
3    x    2
4    y   45
5    z   56

```

---

Or create a 'flag' column in the 'df\_sub', do a `left_join`, and then `filter` based on the `lead/lag` values of 'flag'

```
library(dplyr)
df %>% 
    left_join(df_sub %>%
          mutate(flag = TRUE)) %>%
     filter(flag|lag(flag)|lead(flag)) %>%
     select(-flag)
  var1 var2
1    x    1
2    x    2
3    y   45
4    z   56

```
You can create a row number to keep track of the rows that are selected via join. Subset the data by including minimum row number - 1 and maximum row number + 1.

```
library(dplyr)

tmp <- df %>%
  mutate(row = row_number()) %>%
  inner_join(df_sub, by = c("var1", "var2"))

df[c(min(tmp$row) - 1, tmp$row, max(tmp$row) + 1), ]

#  var1 var2
#2    x    1
#3    x    2
#4    y   45
#5    z   56

```