1

根据关于使用 quosure 作为 by 参数连接数据集的答案,建议使用:quo_name为了使用 quosures 连接表;我想使用as_name/ as_labelas得到相同quo_name的结果,目前处于质疑生命周期阶段

这些功能处于质疑生命周期阶段。

as_label()并且as_name()应该用来代替 quo_name()。 as_label()将任何 R 对象转换为字符串,但只能用于创建默认名称。标签化不是一个定义明确的操作,不应对标签做出任何假设。另一方面, as_name() 仅适用于(可能是quosured)符号,但它是一个定义明确且确定性的操作。

例子

library("tidyverse")

data_a <- tibble(col_ltr = letters, col_nums = seq_along(letters))
data_b <- tibble(col_ltr = letters, col_nums = seq_along(letters) * -1)


clean_and_join <-
    function(data_one,
             data_two,
             column_id_one,
             column_id_two,
             col_nums_one,
             col_nums_two) {

        clean_data_one <- filter(data_one, {{col_nums_one}} %% 2 == 0)
        clean_data_two <- filter(data_two, {{col_nums_two}} %% 2 != 0)

        by_cols <- set_names(as_label({{column_id_one}}), as_label({{column_id_two}}))

        left_join(
            x = clean_data_one,
            y = clean_data_two,
            by = by_cols
        )
    }

clean_and_join(data_one = data_a, data_two = data_b, column_id_one = col_ltr,
               column_id_two = col_ltr, col_nums_one = col_nums,
               col_nums_two = col_nums)

错误

错误is_quosure(x)'col_ltr'找不到对象

期望的结果

left_join(
    x = clean_data_one,
    y = clean_data_two,
    by = c("col_ltr" = "col_ltr") # Or by = "col_ltr" in case of identical name
)
4

1 回答 1

2

一个选项将转换为symbol,然后转换为字符串as_string

clean_and_join <-
    function(data_one,
             data_two,
             column_id_one,
             column_id_two,
             col_nums_one,
             col_nums_two) {

        clean_data_one <- filter(data_one, {{col_nums_one}} %% 2 == 0)
        clean_data_two <- filter(data_two, {{col_nums_two}} %% 2 != 0)

        by_cols <- set_names(rlang::as_string(rlang::ensym(column_id_one)), 
                 rlang::as_string(rlang::ensym(column_id_two)))

        left_join(
            x = clean_data_one,
            y = clean_data_two,
            by = by_cols
        )
    }
  

-测试

clean_and_join(data_one = data_a, data_two = data_b, column_id_one = col_ltr,
                column_id_two = col_ltr, col_nums_one = col_nums,
                col_nums_two = col_nums)
# A tibble: 13 x 3
   col_ltr col_nums.x col_nums.y
#   <chr>        <int>      <dbl>
# 1 b                2         NA
# 2 d                4         NA
# 3 f                6         NA
# 4 h                8         NA
# 5 j               10         NA
# 6 l               12         NA
# 7 n               14         NA
# 8 p               16         NA
# 9 r               18         NA
#10 t               20         NA
#11 v               22         NA
#12 x               24         NA
#13 z               26         NA
于 2020-12-13T22:29:45.937 回答