rhdf5 icon indicating copy to clipboard operation
rhdf5 copied to clipboard

Variable lookup within indexing is broken

Open mschubert opened this issue 4 years ago • 1 comments

This is with the current git master.

Consider the following example file (borrowed from the open PR):

library(rhdf5)
f = h5createFile("ex_hdf5file.h5")
B = array(seq(0.1,2.0,by=0.1),dim=c(5,4))
h5write(B, "ex_hdf5file.h5","B")
h5closeAll()

Subsetting this file works fine if I use:

file = rhdf5::H5Fopen("ex_hdf5file.h5")
myx = 1:2
data = file&"/B"
data[myx,]
h5closeAll()

However, if I wrap the loading in a function it fails:

loadx = function() {
    file = rhdf5::H5Fopen("ex_hdf5file.h5")
    on.exit(rhdf5::H5Fclose(file))
    myx = 1:2
    data = file&"/B"
    data[myx,]
}
loadx()
# Error in eval(index[[i]]) : object 'myx' not found

mschubert avatar Jul 08 '20 19:07 mschubert

Hi, I've just experienced the same bug.

The cause seems to be line 17 in h5read.R using eval(): for whatever reason, this is called in a different environment to the function, so it won't find the variables. Setting them in the global environment will work, but is obviously not the desired behaviour, since global vars will shadow function arguments.

I don't know if the best solution would be to capture the calling environment, eval the index in a different place, or use a less magical solution. For now you can work around this using un-exported functions (note the triple colon :::) from the package like so:

rhdf5:::h5readDataset(my_dataset, start=a, count=N)

mgperry avatar Sep 18 '23 13:09 mgperry