问题
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.
回答1:
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
来源:https://stackoverflow.com/questions/53101245/r-dplyr-merge-in-user-defined-function