Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 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 Answer

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)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...