首页 > 解决方案 > 如何使用 R 读取文件夹中的所有 hdf 文件?

问题描述

我在一个文件夹中有数千个 hdf 文件。有没有办法创建一个循环来读取该文件夹中的所有 hdf 文件并将一些特定数据写入另一个文件?

我使用以下代码读取了文件夹中的第一个文件:

mydata <- h5read("/path to file/name of the file.he5", "/HDFEOS/GRIDS/Northern Hemisphere/Data Fields/SWE_NorthernDaily")

但是我文件夹里还有1686个文件,一个一个读不出来。我想我需要编写一个 for 循环来读取文件夹中的所有文件。

我发现一些代码列出了文件夹中的 txt 文件,然后读取所有文件:

nm <- list.files(path="path/to/file")
do.call(rbind, lapply(nm, function(x) read.table(file=x)[, 2]))

我尝试更改代码,如下所示:

nm <- list.files(path="path/to/file")
do.call(rbind, lapply(nm, function(x) h5read(file=x)[, 2]))

但是错误消息说:

h5checktypeOrOpenLoc(file, readonly = TRUE, native = native) 中的错误:h5checktypeOrOpenLoc() 中的错误。不能打开文件。文件 'D:\path to file\name of the file.he5' 不存在。

在那种情况下我该怎么办?

标签: rloopsfor-loophdf

解决方案


如果您不受特定技术的约束,您可能需要查看HDFql。在R中使用HDFql,您的问题可以解决如下(为了这个例子,假设(1)数据集/HDFEOS/GRIDS/Northern Hemisphere/Data Fields/SWE_NorthernDaily存在于目录中存储的所有HDF5文件中,(2)它有一个维度(大小1024),并且(3) 数据类型为整数):

# load HDFql R wrapper (make sure it can be found by the R interpreter)
source("HDFql.R")

# create variable "values" and initialize it
values <- array(dim = c(1024))
for(x in 1:1024)
{
    values[x] <- as.integer(0)
}

# show (i.e. get) files stored in directory "/path/to/hdf5/files" and populate HDFql default cursor with it
hdfql_execute("SHOW FILE /path/to/hdf5/files")

# iterate HDFql default cursor
while(hdfql_cursor_next() == HDFQL_SUCCESS)
{
    file_name <- hdfql_cursor_get_char()

    # select (i.e. read) data from dataset "/HDFEOS/GRIDS/Northern Hemisphere/Data Fields/SWE_NorthernDaily" and populate variable "values" with it
    hdfql_execute(paste("SELECT FROM", file_name, "\"/HDFEOS/GRIDS/Northern Hemisphere/Data Fields/SWE_NorthernDaily\" INTO MEMORY", hdfql_variable_transient_register(values)))

    # display values stored in variable "values"
    for(x in 1:1024)
    {
        print(values[x])
    }
}

有关如何使用 HDFql 读取数据集的其他示例,请参阅快速入门指南参考手册


推荐阅读