如何从R脚本中的配置文件中获取参数 [英] How to get parameters from config file in R script

查看:24
本文介绍了如何从R脚本中的配置文件中获取参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从 R 脚本中的文件中读取参数?

Is there a way to read parameters from a file in an R script?

我想创建一个配置文件

db_host=xxxx
db_name=xxxx
db_user=xxxx
db_pass=xxxx

然后在 R 脚本中使用它来创建数据库连接.

and then use it in the R script to create DB Connection.

dbConnect(PgSQL(), host="xxxx", dbname="xxxxx", user="xxxx", password="xxxxx")

然后我如何在 R 脚本中使用它.

and then how do I use it in the R Script.

已我还想知道是否有一种方法可以跨 R 脚本、Perl 脚本和使用单个配置文件.爪哇?

EDITED: I also want to know if there is a way in which I can use a single config file across R Scripts, Perl Scripts & Java?

推荐答案

我会选择 YAML.与 XML 不同,专为人类可读性而设计.R 包yaml"存在于 CRAN 上,我确定 perl 和 java 包也存在.

I'd go for YAML. Designed for human read-writability unlike XML. R package "yaml" exists on CRAN, I'm sure perl and java packages exist too.

http://ftp.heanet.ie/mirrors/cran.r-project.org/web/packages/yaml/index.html

没有比这更多的跨平台了:

You can't get more cross-platform than this:

http://yaml.org/

至少在我写一个 YAML FORTRAN 包之前...

at least until I write a YAML FORTRAN package...

示例.假设你有 config.yml:

Example. Suppose you have config.yml:

db:
 host : foo.example.com
 name : Foo Base
 user : user453
 pass : zoom

然后 yaml.load_file("config.yml") 返回:

Then yaml.load_file("config.yml") returns:

$db
$db$pass
[1] "zoom"

$db$user
[1] "user453"

$db$name
[1] "Foo Base"

$db$host
[1] "foo.example.com"

所以你这样做:

library(yaml)
config = yaml.load_file("config.yml")
dbConnect(PgSQL(), host=config$db$host, dbname=config$db$name, user=config$db$user, password=config$db$pass)

根据需要添加尽可能多的部分和参数.亲爱的.

Add as many sections and parameters as you need. Sweeeeyit.

yaml.load_file 将您的配置作为 R 列表返回,您可以使用 $-notation 访问列表的命名元素.

The yaml.load_file returns your configuration as an R list, and you can access named elements of lists using $-notation.

这篇关于如何从R脚本中的配置文件中获取参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆