#--------------------------------------------------------------------------------
IniFile.initialize <-function(filePath){
connection <- file(filePath)
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)
self$IniList <- INI.list
}
#--------------------------------------------------------------------------------
# R6
iniFile <- function(filePath){
IniFile$new(filePath)
}
#--------------------------------------------------------------------------------
IniFile <- R6::R6Class("IniFile",
public = list(
#属性
IniList=NA, # 内容
initialize = IniFile.initialize, #初始化
member = function(){ # member的方法
print(self)
print(private)
print(ls(envir=private))
}
)# end public
)#end class
#--------------------------------------------------------------------------------
#[section] key = value
IniFile$set("public", "readIni", function(section,key=NULL){
if (!is.null (section))
sectionList <- self$IniList[section]
if(is.null(key)){
ToParse <- paste("sectionList$", section)
}else{
ToParse <- paste("sectionList$", section, "$", key)
}
Temp <- eval(parse(text=ToParse))
return(as.list(Temp))
}) # end read.ini
#========================================
调用过程:
1. int <- iniFile('data/Sample.ini')
2.1 temp <- int$readIni(section = 'Files',key = 'name0')
2.2 temp <- int$readIni(section = 'Files')
3. class(temp)
[1] "list"
#======================================
Sample.ini
[SystemSetup]
OlfactometerCode=3
[Files]
prelog0=Part0.txt
date0=2:06:27.461 PM 6/9/2007
note0=group1-1
name0=group1
prelog1=Part1.txt
date1=2:09:16.809 PM 6/9/2007
note1=group1-1
name1=group1-1
[DefaultLevels]
FC00=50
FC01=100
FC02=50
FC10=50
[OdorNames]
port0=None
port1=None
[Map]
port0=0,0,0,0,0,0,0,0,0,0,0,0
port1=0,0,0,0,0,0,0,0,0,0,0,0
port2=0,0,0,0,0,0,0,0,0,0,0,0