The select function can take strings, so you could do the following instead of your first function:
mtcars %>% select(names(mtcars)[c(6,4,2)])
mtcars %>% select(3,1)
iris %>% select(starts_with("Petal"))
iris %>% select(matches("Wid|Spec"))
# Or if you want to shorten it with a function
f = function(d, ...) {
d %>% select(...)
}
mtcars %>% f(names(mtcars)[c(6,4,2)])
mtcars %>% f(3,1)
iris %>% f(starts_with("Petal"))
iris %>% f(matches("Wid|Spec"))
For the joining variables, you can also just return a string vector with the desired join columns. The intersect function will return a vector containing the column names that two data frames have in common (for example, intersect(names(mtcars), names(my_data2)), but left_join already joins by common column names automatically. For example, all of these do the same thing:
left_join(mtcars, my_data2)
left_join(mtcars, my_data2, by=c("mpg", "cyl"))
join_cols = function(x, y) {
intersect(names(x), names(y))
}
mtcars %>%
left_join(my_data2, by = join_cols(., my_data2))
Do you have particular uses case in mind? We can help you construct a function to do the job if you can say more about what you're trying to accomplish.