How to get parameters from config file in R script

前端 未结 4 2024
一整个雨季
一整个雨季 2020-12-08 09:59

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=         


        
4条回答
  •  我在风中等你
    2020-12-08 10:22

    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.

提交回复
热议问题