-4

suppose that we have 2 tables.

First table A:

name    x     y
  a     1     2
  b     3     4
  c     5     7
  d     8     7
  c     5     3
  b     5     4

Second table B:

name    z     w
  a     1     9
  b     3     5
  c     5     2
  d     8     1
  b     5     9

I wish to do left join on these 2 tables on name and x and z, i.e., x and z are basically the same but with different names. Therefore, the final table should look like:

name    x     y    w
  a     1     2    9
  b     3     4    5
  c     5     7    2
  d     8     7    1
  c     5     3    2
  b     5     4    9

Any idea on how to do that in R or SQL?

A.M.
  • 1,757
  • 5
  • 22
  • 41

3 Answers3

0
   SELECT A.NAME,A.X,B.Y.B.W FROM A INNER JOIN B 
   ON 
   A.X=B.Z
VJ Hil
  • 904
  • 6
  • 15
0

In SQL

select A.name, x, y, w
from A
join B
on A.name = B.name and x = z

In dplyr you'll need to rename B's z to x. dplyr will make sure any columns named the same in each are equal.

library(dplyr)
names(B)[which(names(B) == "z")] <- "x"
left_join(A, B)

You can do similar with base functions, see ?merge.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
0

In PostgreSQL:

SELECT * 
FROM "A"
LEFT OUTER JOIN "B"
ON "A".name = "B".name
AND x = w

In r:

Please enter

?merge

on the r command line to see the documentation for the merge function.

This should be something like what you're looking for:

merge(x=A, y=B, by.x = c("name","x"), by.y=c("name","w"), all.x=TRUE)
samhiggins2001
  • 318
  • 2
  • 12