eriee
eriee

Reputation: 396

How to create a dictionary and insert key with a list of value in R?

I want to loop through content of a file, compute the key of each word and then store the words with same key in a list.

In python, it's like below:

dictionary = {}
for word in file:
    key = dosomecalucation(word)
    dictionary.setdefault(key, [])
    dictionary[key].append(word)

In R, how can I declare a dictionary with key as string and value as a list? How can I check whether a key exist in the dictionary?

Upvotes: 0

Views: 1751

Answers (1)

parir
parir

Reputation: 26

You could use the hash package for this task:

library(hash)

h <- hash()

for (word in file) {
    key <- dosomecalculation(word)
    if (!has.key(key, h)) {
        h[key] <- list()
    } else {
        h[key] <- append(h[[key]], word)
    }
}

Using [[ for indexing (e.g. h[["foo"]]) will then return the corresponding list.

Upvotes: 1

Related Questions