r - 如何使用 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' 不存在。
在那种情况下我该怎么办?
解决方案
如果您不受特定技术的约束,您可能需要查看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])
}
}
推荐阅读
- swift - Firebase Firestore 查询未执行
- c++ - 为什么我的班级成员不存在?
- git - 如何在 git 中将 7 个推送的提交压缩为一比一?
- javascript - “未处理的拒绝(SyntaxError):JSON 中位置 0 的意外令牌 h”与 response.json()
- reactjs - 如何在 Gatsby 中集成 whatwg-fetch
- c++ - 在 CIN 上输入 10 位数字时程序永远循环
- javascript - 对象方法内部的设置超时
- java - 如何在 Java OpenCV 中将两点相加?
- python - 将查询集从装饰器传递给函数
- javascript - 将环境变量传递给前端