如何解决如何在R函数中具有不同数量的具有默认值的参数?
我是R语言的新手,他创建了一个函数,该函数可从图中的数据集中突出显示国家列表。
功能问题。如果未将国家/地区名称作为参数传递(可能会有所不同),那么它应该可以从默认国家/地区列表中获取。
我知道getter/setter
用于...
,然后也许可以使用variable arguments
,但是我无法将其与默认值放在一起。
有没有一种我可以写的方式:list(...)
如果我没有提到任何国家,那么它将采用默认国家/地区。
下面是代码(使用gapminder数据进行复制):
country_highlight_plot(Australia,Singapore,Norway)
解决方法
我认为设置合理的默认值并对其进行检查对我来说很有意义。
我倾向于区分NULL
和NA
,其中NULL
的意思是“什么都不用”,而NA
的意思是“使用默认值”。 / p>
未经测试:
country_highlight_plot <- function(df = gapminder,y_var = gdpPercap,background_line_color = "grey",countries = NA) {
if (is.null(countries)) {
countries <- sort(unique(df[["country"]])) # assuming 'country' is in there
} else if (anyNA(countries)) {
countries <- c("India","Singapore","Malaysia","Norway","Denmark","United States","United Kingdom","China")
countries <- intersect(countries,unique(df[["country"]]))
}
# ...
}
这允许一个人将country_highlight_plot(...,countries=NULL)
用于df
中的所有国家,并将country_highlight_plot(...,countries=NA)
用作您的默认国家/地区列表。 intersect
调用可确保如果将此函数作为已过滤的gapminder
数据集的一部分进行调用,则不会查找不存在的国家/地区。 (根据您当前的%in%
使用情况,这可能不是严格必要的...但是,如果您将countries
用于其他任何用途,它可能仍然有用。防御性编程。)
切切地讲:如果您要将功能作为程序包的一部分编写,那么我建议您导入(授权)gapminder
程序包,然后使用类似的技术来使用该数据集:
country_highlight_plot <- function(df,countries = NA) {
if (missing(df)) {
df <- get("gapminder",envir = asNamespace("gapminder"))
}
if (is.null(countries)) {
countries <- sort(unique(df[["country"]])) # assuming 'country' is in there
} else if (anyNA(countries)) {
countries <- c("India","China")
}
# ...
}
您可以这样做
# default data,your default_list
country_highlight_plot()
# default data,all countries
country_highlight_plot(countries = NULL)
# pre-defined data,all default_list countries found
dplyr::filter(gapminder,...) %>%
country_highlight_plot(.)
# pre-defined data,all countries found
dplyr::filter(gapminder,...) %>%
country_highlight_plot(.,countries = NULL)
# default data,manual countries
country_highlight_plot(countries = c("a","B"))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。