Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

r - join datasets using a quosure as the by argument

I am trying to write a custom function that will join two datasets using a quosures as the arguments in the "by = c()" portion of the left_join() function.

Here is my current attempt at the function, which fails at the "by = c(!!left_index = !!right_index))" portion. left_join expects these arguments to be quoted and quoting quosures nullifies the !!.

join_by_quosure <- function(data, left_index, var_to_impute, right_index){
  require(dplyr)

  left_index <- enquo(left_index)
  right_index <- enquo(right_index)
  var_to_impute <- enquo(var_to_impute)

  left_join(data, 
    data %>% select(!!right_index, !!var_to_impute),
    by = c(!!left_index = !!right_index))
}

I have written this working example below of how the function would work:

# join_by_quosure(data = mtcars, left_index = vs, var_to_impute = mpg, right_index = am)

left_join(mtcars, 
          mtcars %>% select(am, mpg),
          by = c("vs" = "am"))

If anyone can offer insight about how to call a quosure within the "by = c()" portion of the left_join() function I would be very grateful.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The c() function doesn't support the rlang bangs so you'll have to take a more traditional approach to building your parameter. You can do

join_by_quosure <- function(data, left_index, var_to_impute, right_index){
  require(dplyr)

  left_index <- enquo(left_index)
  right_index <- enquo(right_index)
  var_to_impute <- enquo(var_to_impute)

  by = set_names(quo_name(right_index), quo_name(left_index))

  left_join(data, 
            data %>% select(!!right_index, !!var_to_impute),
            by = by)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...