1

I want to create a data fame from values in two different data frame containing same values in column ID

Input data

df1<- data.frame(ID = c(102, 205, 333, 434, 512), Order1 = c("ball", 
"ball", "pen", "glass", "scale"))
df2 <- data.frame(ID = c(102, 205, 333, 434, 512), ActOrder1 = c("cap", 
"watch", "cup", "pen", "pencil"), ActOrder2 = c("cap", "fan", "phone", 
"NA",  "NA"))

for all the values of ball in the column Order1 of df1, I want to extract the values in the column ActOrder1 & Actorder2 from df2

Output

df3 <- data.frame(ID = c(102, 205), Order1 = c("ball", "ball"), 
ActOrder1 = c("cap", "watch"), ActOrder2 = c("cap", "fan") )
Community
  • 1
  • 1
Aashay Mehta
  • 118
  • 8
  • Possible duplicate of [How to join (merge) data frames (inner, outer, left, right)](https://stackoverflow.com/questions/1299871/how-to-join-merge-data-frames-inner-outer-left-right) – camille Oct 05 '19 at 18:16
  • I want to extract the values into a new data frame based on a value in column Order1 (ball) of df1. – Aashay Mehta Oct 05 '19 at 18:21
  • Additional the values in the column "Order1" "ActOrder1" and "ActOrder2" do not match. But the corresponding value in the column "ID" matches. – Aashay Mehta Oct 05 '19 at 18:25
  • Since you asked in comments below for more info on left & right joins, the post I flagged this as a duplicate of has 19 answers giving lots of details on different types of joins. Click the link ^^^ – camille Oct 05 '19 at 21:38

1 Answers1

1

We can use a left_join with filter

library(dplyr)
left_join(df1, df2, by = 'ID') %>%
   filter(Order1 == 'ball')  %>%
   select(names(df1), starts_with('ActOrder'))
akrun
  • 874,273
  • 37
  • 540
  • 662