20

I'm currently working on a script which should analyze a dataset based on a 'configuration' file.

The input of this file is for instance:

configuration.txt:

123456, 654321
409,255,265
1

It can contain onther values as well, but they will al be numeric. In the example described above the file should be read in as follows:

timestart <- 123456
timeend <- 654321
exclude <- c(409,255,265)
paid <- 1

The layout of the configuration file is not fixed, but it should contain a starting time (unix) an ending time (unix) an array with numbers to exclude and other fields. In the end it should be constructed from fields a user specifies in a GUI. I don't know which formatting would suit best for that case, but as soon as I have these basics working I don't think that will be a big problem.

But that will make it harder to know which values belong to which variable.

Max van der Heijden
  • 1,095
  • 1
  • 8
  • 16
  • 2
    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. – Andrie Jun 15 '12 at 13:08
  • 3
    Similar question: http://stackoverflow.com/q/5272846/602276 – Andrie Jun 15 '12 at 13:10
  • 1
    As an R user/web developer, I'd suggest JSON. There are `rjson` and `RJSONIO` packages for appropriate (de)serialisation. But IMO `source()`able R scripts are the best way to go, as @Andrie suggested. – aL3xa Jun 15 '12 at 13:12

2 Answers2

32

Indeed, as Andrie suggested, using a .r config file is the easiest way to do it. I overlooked that option completely!

Thus, just make a .r file with the variables already in it:

#file:config.R
timestart <- 123456
timeend <- 654321
exclude <- c(409,255,265)
paid <- 1

In other script use:

source("config.R")

And voila. Thank you Andrie!

Max van der Heijden
  • 1,095
  • 1
  • 8
  • 16
  • Again, I really did not thought of this. Even though it is very simple. Even for later use with the input derived from a website, this can still be used perfectly I guess. – Max van der Heijden Jun 15 '12 at 13:46
  • 1
    This is nice, but ideally I would want to load the settings into a separate namespace so that I am not polluting the list of global variables. I suppose I could define my own named list inside a .R file ... – Leonid Apr 25 '17 at 00:10
9

Another alternative would be to use the config package. This allows setting configuration values to be executed according to the running environment (production, test, etc.). All parameters are accessed by a list and are loaded by a YAML text format configuration file.

More details and examples about config can be found here: https://cran.r-project.org/web/packages/config/vignettes/introduction.html

If you wants to load a JSON, TOML, YAML, or INI text configuration file, see also the configr package.

Giancarlo
  • 131
  • 1
  • 8