MadSeb
MadSeb

Reputation: 8234

Reading a key-value file in R

Is there a way to read a simple text key-value file in R ...

Key1=Value1
Key2=Value2
Key3=Value3

Ideally I want to access the data like this:

myfile$Key1 should return Value1 , myfile@Key2 should return Value2
and so on

Cheers! MadSeb

P.S I looked into the stashR and the filehash packages and while these packages implement nice key value databases, they don't store the database in simple/readable text format.

Upvotes: 4

Views: 2904

Answers (2)

poinck
poinck

Reputation: 21

I corrected the above answer, because I think there is a $value missing when accessing the result:

require(data.table)

rc <- read.csv(file = "~/.rc", header = FALSE, sep = "=",
    col.names = c("key", "value"))
rc_table <- data.table(rc, key = "key")
value1 <- rc_table["key1"]$value

Upvotes: 0

digEmAll
digEmAll

Reputation: 57210

What about something like this:

dframe <- read.table(file='yourfile.txt',header=FALSE,
                     sep='=',col.names=c('Key','Value'))

then, if you want a faster access by key, you can use data.table e.g. :

library(data.table)
dframe <- read.table(file='yourfile.txt',header=FALSE,
                     sep='=',col.names=c('Key','Value'))
dtable <- data.table(dtfrm,key='Key')

dtable['Key1']

Upvotes: 8

Related Questions