在 R 函数中使用 is.null
Use of is.null within function in R
我正在编写一个函数,需要测试某个参数是否为空,在这种情况下需要发生一件事,或者是否已定义,在这种情况下需要发生另一件事。如果已定义,变量将是数据框中的列。这是我的一项尝试的简化示例
test <- function(data, variable) {
if(is.null(variable))
print("NULL")
else
print("Not NULL")
}
因此在这种情况下,test(cars, NULL) 将产生所需的结果,但 test(cars, speed) 将 return 出错(“未找到对象 'speed'”); test(cars, cars$speed) 产生了期望的结果,但不希望用户必须以这种方式定义参数。
我还尝试将上面代码中的 if(is.null(variable)) 更改为 if(is.null(data$variable)) 但随后 test(cars, NULL) 和 test(汽车,速度)打印“NULL”。我也尝试过 if(is.null(~variable)) 但随后 test(cars, NULL) 和 test(cars, speed) 打印“Not NULL.”
如果有人能帮我弄清楚这方面的代码,那就太好了。提前致谢。
编辑:
这是实际功能的略微简化版本。
histogram <- function(data, variable, group = NULL) {
data %>%
ggplot(aes({{ variable }})) +
geom_histogram() +
facet_wrap({{ group }})
}
我想要的是能够调用: histogram(diamonds, price, cut) 而不是需要调用: histogram(diamonds, price, ~cut)。
我最初的想法是确定组是否为 NULL,然后在上面打印的地方有两个不同的 ggplot 函数,一个包含 facet_wrap,另一个不包含。
但是,如下所述,我想做的事情可能非常复杂,所以除非有人有简单的解决方案,否则我想我会坚持使用原样的功能,并要求该组以“~”为前缀.
谢谢大家!
我们可以使用 deparse/substitute
将未加引号的输入转换为字符串,然后在所选列上使用 is.null
。如果该列不存在,它 returns a NULL
可以与 NULL
输入一起捕获,因为 NULL
将转换为 "NULL"
这也是不是数据中的一列
test <- function(data, variable) {
variable <- deparse(substitute(variable))
if(is.null(data[[variable]]))
print("NULL")
else
print("Not NULL")
}
-输出
test(cars, speed)
#[1] "Not NULL"
test(cars, NULL)
#[1] "NULL"
编辑:@Rui Barradas 发表评论后
我正在编写一个函数,需要测试某个参数是否为空,在这种情况下需要发生一件事,或者是否已定义,在这种情况下需要发生另一件事。如果已定义,变量将是数据框中的列。这是我的一项尝试的简化示例
test <- function(data, variable) {
if(is.null(variable))
print("NULL")
else
print("Not NULL")
}
因此在这种情况下,test(cars, NULL) 将产生所需的结果,但 test(cars, speed) 将 return 出错(“未找到对象 'speed'”); test(cars, cars$speed) 产生了期望的结果,但不希望用户必须以这种方式定义参数。
我还尝试将上面代码中的 if(is.null(variable)) 更改为 if(is.null(data$variable)) 但随后 test(cars, NULL) 和 test(汽车,速度)打印“NULL”。我也尝试过 if(is.null(~variable)) 但随后 test(cars, NULL) 和 test(cars, speed) 打印“Not NULL.”
如果有人能帮我弄清楚这方面的代码,那就太好了。提前致谢。
编辑:
这是实际功能的略微简化版本。
histogram <- function(data, variable, group = NULL) {
data %>%
ggplot(aes({{ variable }})) +
geom_histogram() +
facet_wrap({{ group }})
}
我想要的是能够调用: histogram(diamonds, price, cut) 而不是需要调用: histogram(diamonds, price, ~cut)。
我最初的想法是确定组是否为 NULL,然后在上面打印的地方有两个不同的 ggplot 函数,一个包含 facet_wrap,另一个不包含。
但是,如下所述,我想做的事情可能非常复杂,所以除非有人有简单的解决方案,否则我想我会坚持使用原样的功能,并要求该组以“~”为前缀.
谢谢大家!
我们可以使用 deparse/substitute
将未加引号的输入转换为字符串,然后在所选列上使用 is.null
。如果该列不存在,它 returns a NULL
可以与 NULL
输入一起捕获,因为 NULL
将转换为 "NULL"
这也是不是数据中的一列
test <- function(data, variable) {
variable <- deparse(substitute(variable))
if(is.null(data[[variable]]))
print("NULL")
else
print("Not NULL")
}
-输出
test(cars, speed)
#[1] "Not NULL"
test(cars, NULL)
#[1] "NULL"
编辑:@Rui Barradas 发表评论后