在构建R包时如何设置常量变量? [英] How do we set constant variables while building R packages?
问题描述
我们正在R中为我们的服务(巴西的机器人顾问)构建一个程序包,并且我们始终将请求发送到我们函数内部的外部API.
We are building a package in R for our service (a robo-advisor here in Brazil) and we send requests all the time to our external API inside our functions.
因为这是我们第一次构建软件包,所以我们有一些疑问.:(
As it is the first time we build a package we have some questions. :(
当我们使用程序包运行某些脚本时,我们将需要一些信息,例如 api_path,登录名,密码
.
When we will use our package to run some scripts we will need some information as api_path, login, password
.
我们如何将这些信息放入我们的包裹中?
How do we place this information inside our package?
这是一个真实的例子:
get_asset_daily <- function(asset_id) {
api_path <- "https://api.verios.com.br"
url <- paste0(api_path, "/assets/", asset_id, "/dailies?asc=d")
data <- fromJSON(url)
data
}
有时我们使用API的 staging
版本,我们必须不断切换路径.我们应该如何在函数内部调用它?
Sometimes we use a staging
version of the API and we have to constantly switch paths. How we should call it inside our function?
我们应该设置全局环境变量,程序包环境变量,只在脚本或程序包配置文件中定义 api_path
吗?
Should we set a global environment variable, a package environment variable, just define api_path
in our scripts or a package config file?
我们该怎么做?
谢谢您的帮助.
安娜
推荐答案
一种方法是使用R的options接口.使用以下命令在R目录(此文件的惯用名称)中创建文件 zzz.r
:
One approach would be to use R's options interface. Create a file zzz.r
in the R directory (this is the customary name for this file) with the following:
.onLoad <- function(libname, pkgname) {
options(api_path='...', username='name', password='pwd')
}
当程序包加载到内存中时,这将设置这些选项.
This will set these options when the package is loaded into memory.
这篇关于在构建R包时如何设置常量变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!