2

Is there any way I can use a character vector in the 'by' argument of a left_Join in R

I'm trying the following:

DF <- data.frame(a = c("q","a","a","b","b","b","c","c","c","c"), b = c("w","e","r","t","y","u","i","i","w","f"))
DF2 <- data.frame(aa = c("q","a","b","c"), cc = c(1,2,3,4))
DFNames <- names(DF)

left_join(DF,DF2, by = c(DFNames[1] = "aa"))

But I get

Error: unexpected '=' in "left_join(DF,DF2, by = c(DFNames[1] ="

the issue definitely stems from c(DFNames[1] = "aa")

Which returns:

Error: unexpected '=' in "c(DFNames[1] ="

Cheers!

Oliver Humphreys
  • 418
  • 1
  • 5
  • 17

1 Answers1

2

We can do this easily with setNames

out1 <- left_join(DF,DF2, by = setNames("aa", DFNames[1]))

-checking the output

out2 <- left_join(DF, DF2, by = c("a" = "aa"))
identical(out1, out2)
#[1] TRUE
akrun
  • 874,273
  • 37
  • 540
  • 662