我正在尝试使用left_join运算符创建一个复制此函数的函数:
df1 <- data.frame(
name = c("John", "Paul", "George", "Ringo", "Stuart", "Pete"),
instrument = c("guitar", "bass", "guitar", "drums", "bass",
"drums"),stringsAsFactors=FALSE)
df2 <- data.frame(
name2 = c("John", "Paul", "George", "Ringo", "Brian"),
band = c("TRUE", "TRUE", "TRUE", "TRUE", "FALSE"),stringsAsFactors=FALSE)
z <- left_join(df1, df2, by = c("name" = "name2"))
这按预期工作,但是如果我创建这样的函数:
left <- function(x,y,id1) {
left_join(x, y, by = c(id1 = "name2"))
}
left(df1,df2,name)
现在我得到一个错误:
Error: `by` can't contain join column `id1` which is missing from LHS
我一直在和bang bang,quo运算符和!!但是我无法通过传递id1作为参数来使其工作。
注意:这是简化管道(%>%)过程的过程,但主要问题是无法在c()函数内调用id1。
答案 0 :(得分:1)
您可以使用setNames
left <- function(x, y, id1) {
left_join(x, y, by = setNames("name2", id1))
}
left(df1, df2, "name")
# name instrument band
#1 John guitar TRUE
#2 Paul bass TRUE
#3 George guitar TRUE
#4 Ringo drums TRUE
#5 Stuart bass <NA>
#6 Pete drums <NA>