[R] scan or source a text file into a list

Gabor Grothendieck ggrothendieck at myway.com
Thu Nov 11 19:08:40 CET 2004


Andy Bunn <abunn <at> whrc.org> writes:

: 
: I've ported somebody else's rather cumbersome Matlab model to R for
: colleagues that want a free build of the model with the same type of I/O.
: 
: The Matlab model reads a text file with the initial parameters specified as:
: 
: C:\Data\Carluc\Rport>more Params.R
: # Number of years to simulate
: nYears = 50;
: # Initial year for graphing purposes
: year0 = 1970;
: # NPP/GPP ratio (cpp0 unitless)
: fnr = 0.30;
: # Quantum efficency
: qe  = 0.040;
: 
: That is, there are four input variables (for this run - there can be many
: more) written in a way that R can understand them. In R, I can have the
: model source the parameter text file easily enough and have the objects in
: the workspace. The model function in R takes a list at runtime. How can I
: have R read that file and put the contents into the list I need?
: 
: E.g.,
: > rm(list = ls())
: > source("Params.R")
: > ls()
: [1] "fnr"    "nYears" "qe"     "year0"
: > fnr
: [1] 0.3
: > nYears
: [1] 50
: > foo.list <- list(fnr = fnr, nYears = nYears)
: >
: > foo.list
: $fnr
: [1] 0.3
: 
: $nYears
: [1] 50
: 
: 
: The model is then run with
: > CarlucR(inputParamList = foo.list, ...)
: 
: I can't build inputParamList "by hand" as above because the number of
: initial parameters changes with the model run and this runs in a wrapper.
: 


The following sources the file in the environment that
exists within function f returning a list of all variables in
that environment except those variables that begin with a dot. 
You could alternately replace the source(...) statement with 
eval(parse(.file)) .

R> f <- function(.file) { source(.file, local = TRUE); as.list(environment()) }
R> f("clipboard")
$qe
[1] 0.04

$fnr
[1] 0.3

$year0
[1] 1970

$nYears
[1] 50

:




More information about the R-help mailing list