1

I am trying to create a merge function as follows:

Defined function

merge_tables <- function(inputdata1, inputdata2, byvar1, byvar2) {
  
byvar1 <- enquo(byvar1)
byvar2 <- enquo(byvar2)
  
  outputdata <- inputdata1 %>% 
    full_join(inputdata2, by = c(rlang::quo_text(byvar1) = rlang::quo_text(byvar2)))
  
  return(outputdata)
}

I am getting an error when I run using the following data and code:

Mock data

set.seed(1)
data1<- data.frame(ID = sample(1:2), letter1 = sample(letters, 2, replace = TRUE))
data2<- data.frame(PatID = sample(1:3), letter2 = sample(letters, 3, replace = TRUE))

Code using the defined function

testing_merge <- merge_tables(data1, data2, ID, PatID)

Error message

Error: unexpected '=' in:
"  outputdata <- inputdata1 %>% 
    full_join(inputdata2, by = c( (rlang::quo_text(byvar1)) ="
>   
>   return(outputdata)
Error: object 'outputdata' not found
> }
Error: unexpected '}' in "}"

I wonder if anyone can see any glaring issues?... Many thanks.

Community
  • 1
  • 1
Dani
  • 161
  • 9

1 Answers1

2

This should work:

merge_tables <- function(inputdata1, inputdata2, byvar1, byvar2) {

  byvar1 <- enquo(byvar1)
  byvar2 <- enquo(byvar2)

  by <- setNames(quo_name(byvar2), quo_name(byvar1))

  outputdata <- full_join(inputdata1, inputdata2, by = by)

  return(outputdata)

}

Returning:

testing_merge <- merge_tables(data1, data2, ID, PatID)

testing_merge

  ID letter1 letter2
1  1       o       r
2  2       x       q
3  3    <NA>       b
arg0naut91
  • 14,574
  • 2
  • 17
  • 38
  • 1
    Brilliant, thank you! – Dani Nov 01 '18 at 12:54
  • I have a question, is there a reason for the ordering of: setNames(quo_name(byvar2), quo_name(byvar1)). Should byvar1 not come first? – Dani Nov 01 '18 at 12:59
  • 1
    This is due to the nature of `setNames` where simply object comes first and naming later, i.e. `(object = nm)`. It can be confusing, but it is the right approach - I'm sure inversing them would throw you an error. – arg0naut91 Nov 01 '18 at 13:05
  • Indeed, thank you for the clarification. – Dani Nov 01 '18 at 13:07
  • this does not work me with by <- setNames(quo_name(factor), quo_name(`AÑO`)) – Captain Tyler Jul 19 '19 at 14:30