Monday, April 27, 2009

Searching for keyword values in a text (configuration) file in R

Taken from :
https://stat.ethz.ch/pipermail/r-help/2006-September/113841.html

Question :
I would like to read values from an ASCII text file that contains information in the following format:

DEVICE = 'PC'
CPU_SPEED = '1999', '233'
...
How can I e.g. get R to read the 2nd value of CPU_SPEED?

Answer :

Read in data using readLines and replace
= with comma and delete all spaces.
Then reread using read.table and set the
rownames to column 1 removing column 1.

# test data
Lines0 <- "DEVICE = 'PC'
CPU_SPEED = '1999', '233'
"

# if reading from a file then
# replace next line with something like Lines <- readLines("myfile.dat")
Lines <- readLines(textConnection(Lines0))
Lines <- gsub("=", ",", Lines)
Lines <- gsub(" ", "", Lines)
DF <- read.table(textConnection(Lines), sep = ",", fill = TRUE,
colClasses = "character", header = FALSE)
rownames(DF) <- DF[,1]
DF <- DF[,-1]

DF["CPU_SPEED", 2]

No comments:

Post a Comment