NSE 错误处理:使用 NSE/tidy eval 检查 `NA`

问题描述 投票:0回答:1

我正在使用

tidyeval
编写一个函数,我在尝试检查
NA
s 时遇到了问题。

我正在编写一个函数来使用

ggplot2
制作绘图,看起来像:

my_func <- function(data, x = NA, y = NA) {
  if(is.na(x) & is.na(y)) {
    stop("`x` and `y` cannot both be NA.")
  }
  if(is.na(y)) {
    data %>%
      ggplot2::ggplot(ggplot2::aes(x = {{ x }})) + 
      ggplot2::geom_bar()
  } else {
    data %>%
      ggplot2::ggplot(ggplot2::aes(y = {{ y }})) + 
      ggplot2::geom_bar()
  }
}

错误是:

data("iris")
my_func(data = iris, x = Species)

#> Error in my_func(data = iris, x = Species) :
#>   object 'Species' not found

我一直在从 Advanced R 学习 NSE 和元编程,但我对这个话题还是比较陌生。

我已经使用

NA
s和
is.na
以及
NULL
s和
is.null
尝试了这个通用功能。我知道我遗漏了一些关于 NSE 的东西。

r metaprogramming tidyeval
1个回答
1
投票

我们可以用

missing
创造条件

my_func <- function(data, x, y) {
  
  if(missing(y)) {
    data %>%
      ggplot2::ggplot(ggplot2::aes(x = {{ x }})) + 
      ggplot2::geom_bar()
  } else {
    data %>%
      ggplot2::ggplot(ggplot2::aes(y = {{ y }})) + 
      ggplot2::geom_bar()
  }
}

-测试

> my_func(iris, x = Sepal.Length)
> my_func(iris, y = Sepal.Width)
© www.soinside.com 2019 - 2024. All rights reserved.