chilifan
chilifan

Reputation: 185

Subset a data frame on two conditions exclusively for each row

I have a data frame from which I want to extract rows with a specific value in one column and another specific value in the other column. I want to go from df to df_final like in the code below:

x = c(25,25,25,25,44,44,44,44,44,76,76)
y = c(1,2,3,4,1,4,6,7,9,4,3)


df<- data.frame(x,y)

df1 <- df %>% filter(x == 25 & y == 2)
df2 <- df %>% filter(x == 44 & y == 6)
df3 <- df %>% filter(x == 76 & y == 3)

df_final <- rbind(df1,df2,df3)


# desired result:

print(df_final)
   x y
1 25 2
2 44 6
3 76 3

I have tried using filter with dplyr, but dplyr matches everything within filtered x and y, resulting in too many rows, demonstrated below:

df_final <- df %>% filter(x %in% c(25,44,76) & y %in% c(2,6,3))


# non-desired result:

print(df_final)
   x y
1 25 2
2 25 3
3 44 6
4 76 3

Is there a way to match exclusively using dplyr? The first instance in filtered x to the first in filtered y, the second instance in filtered x to the second in filtered y and so on... (Other packages than dplyr is also ok of course)

Upvotes: 0

Views: 34

Answers (1)

det
det

Reputation: 5232

you can make 1 condition and then use eval and parse:

x_cond <- c(25, 44, 76)
y_cond <- c(2, 6, 3)
final_cond <- map2_chr(x_cond, y_cond, ~str_c("x == ", .x, " & y == ", .y)) %>%
  str_c(collapse = " | ")
df %>% filter(eval(parse(text = final_cond)))

Upvotes: 1

Related Questions