1

I know how to join like so:

library(dplyr)

d1 <- data_frame(
  x = letters[1:3],
  y = LETTERS[1:3],
  a = rnorm(3)
  )

d2 <- data_frame(
  x2 = letters[3:1],
  y2 = LETTERS[3:1],
  b = rnorm(3)
  )

left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))

What can I do when column y2 is called:

bla y2

I tried various approaches without success:

left_join(d1, d2, by = c("x" = "x2", "y" = "bla y2"))
left_join(d1, d2, by = c("x" = "x2", "y" = "`bla y2`"))
left_join(d1, d2, by = c("x" = "x2", "y" = `bla y2`))
zx8754
  • 52,746
  • 12
  • 114
  • 209
cs0815
  • 16,751
  • 45
  • 136
  • 299
  • 2
    You don't need to specify column names (index is enough): `base::merge(d1, d2, 1:2)` – pogibas May 17 '19 at 12:04
  • 2
    your first attempt (`"y" = "bla y2"`) works fine for me (`dplyr` version 0.8.0.9001). – Ben Bolker May 17 '19 at 12:16
  • What does "without success" mean exactly? Did you get an error? An unexpected result? It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. (it would be nice to see your non-working an example rather than an example that does work). – MrFlick May 17 '19 at 15:07

1 Answers1

0

In R, you can always specify a column name with backticks, as in:

`bla y2`

But you don't need to do that when passing column names to left_join. This should work:

library(dplyr)

d1 <- data_frame(
  x = letters[1:3],
  y = LETTERS[1:3],
  a = rnorm(3)
)

d2 <- data_frame(
  x2 = letters[3:1],
  `bla y2` = LETTERS[3:1],
  b = rnorm(3)
)

left_join(d1, d2, by = c("x" = "x2", "y" = "bla y2"))

Returns:

# A tibble: 3 x 4
  x     y          a      b
  <chr> <chr>  <dbl>  <dbl>
1 a     A      0.349  0.629
2 b     B     -0.208  0.547
3 c     C     -0.562 -1.16 
C8H10N4O2
  • 18,312
  • 8
  • 98
  • 134