24

My problem is that I would like to do a left join with dplyr like this:

x <- left.join(TableA, TableB)

How can I do to bring just a specific field from TableB? Imagine TableB has 3 fields x,y,z and I just want x in TableA

pogibas
  • 27,303
  • 19
  • 84
  • 117
Suanbit
  • 471
  • 1
  • 4
  • 12
  • What field do you want to match the two tables on? Use use `select()` to keep only the columns for joining and whatever columns you want to merge in. It would be easier to help with a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – MrFlick Sep 06 '17 at 14:30
  • 7
    You can use `select` to keep only those vars in `TableB` first: `x <- TableA %>% left_join(select(TableB, id, x), by = "id")` – austensen Sep 06 '17 at 14:31
  • but in the example that you said "id" is the common var in each table to join the two tables, What I want to do is... imagine TableA containds the vars "id" and "euros", TableB has "id" - "city" - "country". What I want to do is bring city(which is on tableB) to tableA but only that field not "country " for exameple. – Suanbit Sep 07 '17 at 16:55

3 Answers3

39

To join both tables as desired, you have to select field x and an id-field from TableB for the join. You can do this with the select() function. Let's assume for the join that your id-field in TableB is y.

x <- TableA %>% 
  left_join(select(TableB, x, y), by = c("id" = "y"))
0

You subset TableB first. So you do something like:

TableB <- TableB[,'x,']

left_join(TableA,TableB)

The obvious disadvantage of this method is that we are bound to join with column x. Suppose you want to join with column y but want only x in the end result, then you can do the following:

select(left_join(TableA,TableB, by = 'y'), -c(y,z))
Adhishwar
  • 41
  • 10
-2

x <- TableA %>% left_join(select(TableB, id), by.x = "id")

Sandeep
  • 45
  • 1
  • 5
  • That joins all fields in tableB to tableA by "id". I want to join just one var from tableB to tableA :) Thanks! – Suanbit Sep 07 '17 at 16:56