How to Deal with Hdf5 Files in R

reading data frame stored in HDF5

I don't know which package are you using, but using rhdf5 package, it looks very easy to write/read hdf5 files.

## uncomment the 2 lines after to install the package
## source("http://bioconductor.org/biocLite.R")
## biocLite("rhdf5")
library(rhdf5)
## empty HDF5 file : the data base
h5createFile("myhdf5file.h5")
## create group hierarchy. : tables or datasets
h5createGroup("myhdf5file.h5","group1")
h5createGroup("myhdf5file.h5","group2")

## save a matrix
A = matrix(1:10,nr=5,nc=2)
h5write(A, "myhdf5file.h5","group1/A")

## save an array with attribute
B = array(seq(0.1,2.0,by=0.1),dim=c(5,2,2))
attr(B, "scale") <- "liter"
h5write(B, "myhdf5file.h5","group2/B")
## check the data base
h5ls("myhdf5file.h5")

group name otype dclass dim
0 / group1 H5I_GROUP
1 /group1 A H5I_DATASET INTEGER 5 x 2
2 / group2 H5I_GROUP
3 /group2 B H5I_DATASET FLOAT 5 x 2 x 2

## read A and B
D = h5read("myhdf5file.h5","group1/A")
E = h5read("myhdf5file.h5","group2/B")

How to Make a RasterBrick from HDF5 Files? R

One option is using gdalUtils to convert the hdf5 files into GTiff. Once you did that you can read them in a stack. Here is an example code:

# list all the `hdf5` files 
files <- list.files(path=".", pattern=paste(".*.h5",sep=""), all.files=FALSE, full.names=TRUE)
#choose the band that you want using the sds[] option and write GTiff files.
for (i in (files)) {
sds <- get_subdatasets(i)
r2 <- gdal_translate(sds[1], dst_dataset =paste(i,".tif",sep=""))}


Related Topics



Leave a reply



Submit