gpt4 book ai didi

r - 使用可选参数在 R 中编写 ggplot 函数

转载 作者:行者123 更新时间:2023-12-04 10:05:21 30 4
gpt4 key购买 nike

我有一系列 ggplot 图,我在重复一些小的变化。我想将这些带有选项的 qplots 包装到一个函数中,以避免代码中的大量重复。

我的问题是,对于某些图形,我使用了 + facet_wrap() 选项,但对于其他图形,我没有使用。 IE。我需要 facet wrap 作为一个可选参数。当它被包含时,代码需要使用 facets 参数中提供的变量调用 +facet_wrap()。

所以理想情况下,我的函数看起来像这样,facets 是一个可选参数:

$ qhist(variable, df, heading, facets)

我试过在谷歌上搜索如何添加可选参数,他们建议要么传递默认值,要么使用带有 missing() 函数的 if 循环。我也无法上类。

这是我编写的函数,还包括可选的 facets 参数的所需功能。
$ qhist <- function(variable, df, heading, facets) {
qplot(variable, data = df, geom = "histogram", binwidth = 2000,
xlab = "Salary", ylab = "Noms") +
theme_bw() +
scale_x_continuous(limits=c(40000,250000),
breaks=c(50000,100000,150000,200000,250000),
labels=c("50k","100k","150k","200k","250k")) +
opts(title = heading, plot.title = theme_text(face = "bold",
size = 14), strip.text.x = theme_text(size = 10, face = 'bold'))
# If facets argument supplied add the following, else do not add this code
+ facet_wrap(~ facets)

最佳答案

设置默认值的方法是这样的:

testFunction <- function( requiredParam, optionalParam=TRUE, alsoOptional=123 ) {
print(requiredParam)
if (optionalParam==TRUE) print("you kept the default for optionalParam")
paste("for alsoOptional you entered", alsoOptional)
}

* 编辑*

哦,好的...所以我想我对你在问什么有了更好的了解。看起来您不确定如何将可选方面带入 ggplot 对象。这个怎么样:
  qhist <- function(variable, df, heading, facets=NULL) {
d <- qplot(variable, data = df, geom = "histogram", binwidth = 2000,
xlab = "Salary", ylab = "Noms") +
theme_bw() +
scale_x_continuous(limits=c(40000,250000),
breaks=c(50000,100000,150000,200000,250000),
labels=c("50k","100k","150k","200k","250k")) +
opts(title = heading, plot.title = theme_text(face = "bold",
size = 14), strip.text.x = theme_text(size = 10, face = 'bold'))
# If facets argument supplied add the following, else do not add this code
if (is.null(facets)==FALSE) d <- d + facet_wrap(as.formula(paste("~", facets)))
d
return(d)
}

我根本没有测试过这段代码。但一般的想法是 facet_wrap 需要一个公式,所以如果 facet 作为字符串传递,你可以用 as.formula() 构建一个公式。然后将其添加到绘图对象中。

如果我这样做,我会让函数接受一个可选的构面公式,然后将该构面公式直接传递给 facet_wrap .这将否定对 as.formula() 的需要。调用将文本转换为公式。

关于r - 使用可选参数在 R 中编写 ggplot 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8043247/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com