Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. # Dummy example
  2.  
  3. # Large df
  4. df <- mtcars[1:6,1:3]
  5. df$car_1 <- rownames(df)
  6. df$car_2 <- rownames(tail(mtcars))
  7.  
  8. # df to match
  9. mdf <- df[c("car_1","car_2")][3:6,]
  10.  
  11. rownames(df) <- NULL
  12. rownames(mdf) <- NULL
  13.  
  14. mpg cyl disp car_1 car_2
  15. 22.8 4 108 Datsun 710 Ford Pantera L
  16. 21.4 6 258 Hornet 4 Drive Ferrari Dino
  17. 18.7 8 360 Hornet Sportabout Maserati Bora
  18. 18.1 6 225 Valiant Volvo 142E
  19.  
  20. names(mdf) <- c("car_3", "car_4")
  21. merge(df, mdf, by.x = c("car_1", "car_2"), by.y = c("car_3", "car_4"),
  22. all.x = FALSE, all.y = TRUE)
  23.  
  24. library(dplyr)
  25. inner_join(df, mdf)
  26.  
  27. #Joining by: c("car_1", "car_2")
  28. # car_1 car_2 mpg cyl disp
  29. #1 Datsun 710 Ford Pantera L 22.8 4 108
  30. #2 Hornet 4 Drive Ferrari Dino 21.4 6 258
  31. #3 Hornet Sportabout Maserati Bora 18.7 8 360
  32. #4 Valiant Volvo 142E 18.1 6 225
  33.  
  34. df[match(interaction(mdf[c("car_1", "car_2")]), interaction(df[c("car_1", "car_2")])),]
  35.  
  36. df[match(paste(mdf$car_1, mdf$car_2), paste(df$car_1, df$car_2),),]
  37.  
  38. df[interaction(df[c("car_1", "car_2")]) %in% interaction(mdf[c("car_1", "car_2")]),]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement