Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get parameters from config file in R script

Tags:

unix

r

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?

like image 888
Salman A. Kagzi Avatar asked Mar 11 '11 12:03

Salman A. Kagzi


People also ask

How do I read a config file in R?

Simply write the config file as a . r file containing code exactly as you wrote it, then source() it. The variables will then be defined in your environment.

What is config R?

The config package makes it easy to manage environment specific configuration values. For example, you might want to use distinct values for development, testing, and production environments. You can install the config package from CRAN as follows: install.packages("config")


2 Answers

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.

like image 151
Spacedman Avatar answered Oct 19 '22 21:10

Spacedman


You can source() an R script in at the top of your main script that reads in your config file parameters. Depending on who you are sharing your scripts with, there may be issues with database security and having the login information in an unencrypted format. There is a recent question here on SO about that, I'll see if I can find it in a minute.

Anyways, store all of your db parameters in a file named config.R and then on your main script, run:

source("config.R") #Will create four objects named "db_host, db_name, db_user, db_pass"  dbConnect(PgSQL(), host=db_host, dbname=db_name, user=db_user, password=db_pass) 
like image 42
Chase Avatar answered Oct 19 '22 22:10

Chase