Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

unix - How to get parameters from config file in R script

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

I want to create a config file that has

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

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

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/

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

[edit]

Example. Suppose you have config.yml:

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

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"

So you do:

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[3] html - How to create even cell spacing within a

1.4m articles

1.4m replys

5 comments

56.8k users

...