Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse INI like configuration files with R?

Tags:

r

ini

Is there an R function for parsing INI like configuration files?

While searching I only found this discussion.

like image 278
Karsten W. Avatar asked Nov 01 '22 07:11

Karsten W.


1 Answers

Here is an answer that was given to exact the same question on r-help in 2007 (thanks to @Spacedman for pointing this out):

Parse.INI <- function(INI.filename) 
{ 
  connection <- file(INI.filename) 
  Lines  <- readLines(connection) 
  close(connection) 

  Lines <- chartr("[]", "==", Lines)  # change section headers 

  connection <- textConnection(Lines) 
  d <- read.table(connection, as.is = TRUE, sep = "=", fill = TRUE) 
  close(connection) 

  L <- d$V1 == ""                    # location of section breaks 
  d <- subset(transform(d, V3 = V2[which(L)[cumsum(L)]])[1:3], 
                           V1 != "") 

  ToParse  <- paste("INI.list$", d$V3, "$",  d$V1, " <- '", 
                    d$V2, "'", sep="") 

  INI.list <- list() 
  eval(parse(text=ToParse)) 

  return(INI.list) 
} 

Actually, I wrote a short and presumably buggy function (i.e. not covering all corner cases) which works for me now:

read.ini <- function(x) {
    if(length(x)==1 && !any(grepl("\\n", x))) lines <- readLines(x) else lines <- x
    lines <- strsplit(lines, "\n", fixed=TRUE)[[1]]
    lines <- lines[!grepl("^;", lines) & nchar(lines) >= 2]  # strip comments & blank lines
    lines <- gsub("\\r$", "", lines)
    idx <- which(grepl("^\\[.+\\]$", lines))
    if(idx[[1]] != 1) stop("invalid INI file. Must start with a section.")

    res <- list()
    fun <- function(from, to) {
        tups <- strsplit(lines[(from+1):(to-1)], "[ ]*=[ ]*")
        for (i in 1:length(tups)) 
            if(length(tups[[i]])>2) tups[[i]] <- c(tups[[i]][[1]], gsub("\\=", "=", paste(tail(tups[[i]],-1), collapse="=")))
        tups <- unlist(tups)
        keys <- strcap(tups[seq(from=1, by=2, length.out=length(tups)/2)])
        vals <- tups[seq(from=2, by=2, length.out=length(tups)/2)]
        sec <- strcap(substring(lines[[from]], 2, nchar(lines[[from]])-1))
        res[[sec]] <<- setNames(vals, keys)
    }
    mapply(fun, idx, c(tail(idx, -1), length(lines)+1))
    return(res)
}

where strcap is a helper function that capitalizes a string:

strcap <- function(s) paste(toupper(substr(s,1,1)), tolower(substring(s,2)), sep="")

There are also some C solutions for this, like inih or libini that might be useful. I did not try them out, though.

like image 172
Karsten W. Avatar answered Nov 04 '22 08:11

Karsten W.