检查对象是否为空或未定义 [英] Check if object is Null or undefined

查看:53
本文介绍了检查对象是否为空或未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含可选变量参数的函数.默认情况下,我将变量设置为 NULL ,但是如果不是 NULL ,我希望函数执行一些操作.我需要一种方法来检查变量是否不为null.这很复杂,因为我正在使用tidyeval,并且仅使用 is.null(var)会引发未找到对象错误.我找到了一个使用 try 的骇人解决方案,但希望有更好的方法.

I have a function that includes an optional variable parameter. By default, I set the variable to NULL, but if it isn't NULL I'd like my function to do some stuff. I need a way to check if the variable is not null. This is complicated because I am using tidyeval, and just using is.null(var) throws an object not found error. I've found a hacky solution using try, but am hoping there's a better way.

library(dplyr)
dat <- data.frame(value = 1:8, 
                         char1 = c(rep("a", 4), rep("b", 4)), 
                         char2 = rep(c(rep("c", 2), rep("d", 2)), 2))

myfun <- function(dat, group = NULL, var = NULL) {
    
    x <- dat %>% 
        group_by({{group}}, {{var}}) %>% 
        summarize(mean = mean(value), 
                            .groups = "drop")
    
    # if(!is.null(var)) { # Throws object not found error if not null

    null_var <- try(is.null(var), silent = TRUE)
    null_var <- null_var == TRUE
    if(!null_var)   {
        print("do something with `var`")
    }
    x
}
myfun(dat)
myfun(dat, char1)
myfun(dat, char1, char2)

推荐答案

{{ enquo() !! 的组合一步.要检查 var 的内容,您需要分解这两个步骤. enquo()取消对参数的使用,并返回一个您可以检查的保证. !! 将quasure注入其他调用中.

{{ is the combination of enquo() and !! in one step. To inspect the contents of var, you need to decompose these two steps. enquo() defuses the argument and returns a quosure that you can inspect. !! injects the quosure into other calls.

下面,我们在函数开始处 enquo()自变量.使用 quo_is_null()进行检查(您也可以使用 quo_get_expr()来查看其中的内容).然后用 !! 将它注入 group_by()内:

Below we enquo() the argument at the start of the function. Inspect it with quo_is_null() (you could also use quo_get_expr() to see what's inside it). Then inject it inside group_by() with !!:

myfun <- function(dat, group = NULL, var = NULL) {
    var <- enquo(var)
    
    if (!quo_is_null(var)) {
        print("It works!")
    }

    # Use `!!` instead of `{{` because we have decomposed the
    # `enquo()` and `!!` steps that `{{` bundles
    dat %>% 
        group_by({{ group }}, !!var) %>% 
        summarize(mean = mean(value), .groups = "drop")
}

这篇关于检查对象是否为空或未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆