【问题标题】:How to reconcile .data pronouns with rlang::enquo如何协调 .data 代词与 rlang::enquo
【发布时间】:2021-03-12 16:33:33
【问题描述】:

我正在编写一个使用大量 dplyr 函数的包 - 为了通过 devtools::check() 中的所有测试,我必须经常使用 .data。一些函数嵌套在其他函数中。在下面的示例中,我需要在tidyselect 上下文和标准评估中(在创建id) 的部分)中使用variable

df <- data.frame(
  V1 = 1:8,
  V2 = rep(1:4,2)
)

test <- function(df, variable){
  
  x <- df %>%
    mutate(y = {{variable}} + 1)

  id <- rlang::as_name(rlang::enquo(variable))
  
  id_eq <- outer(df[[id]], df[[id]], `==`)
  
  list(x, id_eq)
}

如果没有在 CMD 检查中收到任何警告或注释,我不知道如何处理此问题。 如果我运行test(df = df, variable = V1),则该功能有效,但不适用于test(df = df, variable = .data$V1)

【问题讨论】:

  • 嗨 Arthur,.data.env 背后的一般直觉是 disambiguate whether the name refers to a column in a data frame or a variable in the environment。但是,您的函数在.env$V1 下的行为方式有点不清楚。 mutate() 语句很明显,但是当用户提供.env$myvar 时,outer() 语句应该发生什么?
  • @ArtemSokolov 这就是我的意思,我正在寻找一种方法,以便用户提供 variable 以通过 devtools::check()``´ at the same time that this variable could either work in the outer``` 部分(例如 outer(df[['V1']], df[['V1']], `==`) 或内部 @ 987654340@

标签: r dplyr rlang tidyselect


【解决方案1】:

一种选择是让 tidyverse 完成查找正确变量的工作。将此工作的输出存储到一个临时变量中,并在整个函数中使用该变量:

test <- function(df, variable){

    tmp <- df %>% mutate( .tmp = {{variable}} ) %>% pull(.tmp)

    x <- df %>%
        mutate(y = tmp + 1)

    id_eq <- outer(tmp, tmp, `==`)

    list(x, id_eq)
}

该函数适用于所有有意义的变量引用,包括.data.env 代词:

test( df, V1 )
test( df, .data$V1 )

V1 <- 11:18
test( df, .env$V1 )

【讨论】:

  • 谢谢!在我需要对数据进行子集化的上下文中怎么样,例如id_eq &lt;- df[[1:3, variable]]。我该如何调整它以使其正常工作?它也将嵌套在问题中的函数中
  • @ArthurCarvalhoBrito id_eq &lt;- tmp[1:3] 不会成功吗?也许我错过了大局。
猜你喜欢
  • 1970-01-01
  • 2018-09-14
  • 1970-01-01
  • 2019-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多