Thomas of the Scotts
Thomas of the Scotts

Reputation: 60

Vectorize Environment Access in R

So I have created an environment (which I am trying to use as a hashtable).

To clarify I'm accessing the values stored in the environment with this:

    hash[["uniqueIDString"]] ## hash takes a uniqueID and returns a 
                             ## dataframe subset that is precomputed

I also have a function called func which returns some subset of the rows returned by hash. It works fine for single calls but it isn't vectorized so I can't use it in a transform which is kind of vital.

The following doesn't work:

    df <- transform(df,FOO = func(hash[[ID]])$FOO)

It gives me an error about having the wrong number of arguments for the hash which I presume is because it's passing a vector of IDs to my environment and the environment doesn't know what to do.

EDIT: The exact error is:

    Error in hash[[ID]] : 
      wrong arguments for subsetting an environment

EDIT: With Rob's suggestion I receive the following error:

    Error in hash[ID] : 
      object of type 'environment' is not subsettable

EDIT: For clarification I'm attempting to use the hash lookup in the context of a transform where the values in the ID column are looked up in the hashtable and passed to func so that the output can become a new column.

Upvotes: 1

Views: 3171

Answers (1)

Alex Vorobiev
Alex Vorobiev

Reputation: 4359

I use environments as hash tables a lot, the way to retrieve values corresponding to multiple keys is to usemget:

hash <- new.env()
hash[['one']] <- 'this is one'
hash[['two']] <- 'this is two'
mget(c('one', 'two'), envir = hash)

which returns a list

$one
[1] "this is one"

$two
[1] "this is two"

If you need the output as a vector, use unlist:

unlist(mget(c('one', 'two'), envir = hash))

gives you

          one           two 
"this is one" "this is two" 

UPDATE If your IDs come from a data frame, you'd need to use unlist to convert that column to vector:

df <- data.frame(id=c('one', 'two'))
unlist(mget(unlist(df$id), envir = hash))

Upvotes: 4

Related Questions