dplyr: How to select join columns by name?

Viewed 1630

I would like to use dplyr's left_join to tranfer values ("new") from one DF to another.

How can I do that if I do not know the name of the key, but only know that it is the first variable in the dataset?

require("dplyr")

testData1 <- data.frame(idvar=c(1,2,3),
                    b=c("a","b","c"),
                    c=c("i","ii","iii"))

testData2 <- data.frame(identification=c(1,2),
                    b=c("a","b"),
                    c=c("i","NA"),
                    new=c("var1","var2"))

# now do a left join to obtain values of the new variable in the old dataset


(testResult1 <- left_join(testData1,testData2))
# var2 is not in the results because of the "NA" in testData2!


(testResult2 <- left_join(testData1,testData2,
                         by=c("idvar"="identification"))) 
# works as expected! ... but we do not know the name of the idvar!


(testResult3 <- left_join(testData1,testData2,
                         by=c(names(testData1)[1]=names(testData2)[1]))) 
# Error: unexpected '=' in:
#   "testResult3 <- left_join(testData1,testData2,
#                             by=c(names(testData1)[1]="
2 Answers
Related