[R] Read Windows-like .INI files into R data structure?
Uwe Ligges
ligges at statistik.uni-dortmund.de
Wed Jun 13 11:29:04 CEST 2007
Vladimir Eremeev wrote:
>
> Christophe Pallier wrote:
>>> "var1=value1", "A=value3" is almost pure R code.
>>> Is it possible to use this feature to solve the problem?
>> Along the same lines: you may write a short script that converts the ini
>> file into R code that can be sourced.
>>
>> >From your example, you can generate the following R code:
>>
>> Section1 <- list()
>> Section1['var1'] <- value1
>> Section1['var2'] <- value2
>> Section2 <- list()
>> Section2['A'] <- value3
>> Section2['B'] <- value4
>>
>>
>> with the following awk script (using awk -F'=' -f conv.awk example.ini >
>> example.R)
>>
>> ### conv.awk
>> $1 ~ /\[/ { gsub(/[\[\]]/,""); # remove the brackets
>> listname = $1;
>> print $1 " <- list()";
>> next }
>> { print listname "['" $1 "'] <- " $2 }
>>
>> (I know, it looks cryptic... so I am shooting myself in the foot after
>> claiming that awk scripts are typically quite readable ;-)
>>
>> Christophe Pallier (http://www.pallier.org)
>>
>
> It's sufficiently readable, but using something besides R is not sporty. ;)
OK, I try to be sporty, at least that is what my family doctor asks me
to do all the time ;-)
Certainly there is much space for improvements...
X <- readLines(file)
value1 <- 1
value2 <- 2
value3 <- 3
value4 <- 4
sections <- grep("^\\[.*\\]$", X)
starts <- sections + 1
ends <- c(sections[-1] - 1, length(X))
L <- vector(mode="list", length=length(sections))
names(L) <- gsub("\\[|\\]", "", X[sections])
for(i in seq(along = sections)){
env <- new.env()
eval(parse(text=X[seq(starts[i], ends[i])]), env = env)
L[[i]] <- as.list(env)
}
More information about the R-help
mailing list