R 如何在ggplot函数内传递可选参数
我想将R 如何在ggplot函数内传递可选参数,r,ggplot2,optional-parameters,R,Ggplot2,Optional Parameters,我想将plot1函数中的ybreak参数设置为可选参数。如果未指定此参数(NULL条件),则我只想返回gggplot,否则使用自定义ybreak。我通过引用类似的答案尝试了以下代码,但它就是不起作用 plot1 <- function(df, x, y, ybreak = NULL) { g <- ggplot(df, aes_string(x = x, y = y)) if (is.na(ybreak) == F) { g + scale_y_continuou
plot1
函数中的ybreak
参数设置为可选参数。如果未指定此参数(NULL
条件),则我只想返回g
ggplot,否则使用自定义ybreak
。我通过引用类似的答案尝试了以下代码,但它就是不起作用
plot1 <- function(df, x, y, ybreak = NULL) {
g <- ggplot(df, aes_string(x = x, y = y))
if (is.na(ybreak) == F) {
g + scale_y_continuous(breaks = ybreak)
}
else {
g
}
}
plot1(mtcars, x = "mpg", y = "disp")
plot1(mtcars, x = "mpg", y = "disp", ybreak = seq(70, 500, by = 50))
> plot1(mtcars, x = "mpg", y = "disp")
Error in if (is.na(ybreak) == F) { : argument is of length zero
> plot1(mtcars, x = "mpg", y = "disp", ybreak = seq(70, 500, by = 50))
Warning message:
In if (is.na(ybreak) == F) { :
the condition has length > 1 and only the first element will be used
plot1 plot1(mtcars,x=“mpg”,y=“disp”,ybreak=seq(70500,by=50))
警告信息:
在if(is.na(ybreak)==F){
条件的长度大于1,并且只使用第一个元素
第一种情况:ybreak=NULL
is.na(NULL)
返回:
因此(因为逻辑(0)什么都不是):
返回:
但是如果我们使用is.null
(null
什么都不是)而不是is.na
(na
是一些东西(只是不是数字)):
返回:
然后:
is.null(NULL) == FALSE
第二种情况:ybreak=seq(70500,by=50)
但是我们可以使用all
一次检查多个布尔值:
if (all(is.na(seq(70, 500, by = 50)) == FALSE)) print("something")
注意:请参见下面的编辑 R的省略号或三点功能用于处理可选参数。如果您的函数将有更多可选参数,这可能会很有用。在您提供的示例中,请按以下方式构造输入参数
plot1尝试如果(!is.null(ybreak)){…
它能工作!非常感谢。但是,我还是不明白为什么is.na(ybreak)==F
不工作。is.na(null)==FALSE
计算结果为逻辑(0)
和is.na(c(1,2,3))
计算为一个向量FALSE,FALSE,FALSE
。这就是警告消息试图说的:得到了一个只需要一个元素的向量。这会清除它吗?@dario这非常有用。它会清除一切。
logical(0)
is.null(NULL)
[1] TRUE
is.null(NULL) == FALSE
[1] FALSE
is.na(seq(70, 500, by = 50))
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
if (is.na(seq(70, 500, by = 50)) == FALSE) print("something")
[1] "something"
Warning message:
In if (is.na(seq(70, 500, by = 50)) == FALSE) print("something") :
the condition has length > 1 and only the first element will be used
if (all(is.na(seq(70, 500, by = 50)) == FALSE)) print("something")
l[1] "something"
plot1 <- function(df, x, y, ...) {
- args <- eval(substitute(alist(...)))
- inputs <- purrr::map(args, as.list)
+ args <- rlang::list2(...)
# evaluate arguments using
# args$my_optional_argument or
# args[["my_optional_argument"]]
}