file <- tempfile(fileext = ".h5")
# 1. Writing Basic Datasets
h5_write(1:10, file, "data/integers")
h5_write(rnorm(10), file, "data/floats")
h5_write(letters[1:5], file, "data/chars")
# 2. Writing Attributes
# Write an object first
h5_write(1:10, file, "data/vector")
# Attach an attribute to it using the 'attr' parameter
h5_write(I("My Description"), file, "data/vector", attr = "description")
h5_write(I(100), file, "data/vector", attr = "scale_factor")
# 3. Controlling Data Types
# Store values as 32-bit signed integers
h5_write(1:5, file, "small_ints", as = "int32")
# 4. Writing Complex Structures (Lists/Groups)
my_list <- list(
meta = list(id = 1, name = "Experiment A"),
results = matrix(runif(9), 3, 3),
valid = I(TRUE)
)
h5_write(my_list, file, "experiment_1", as = c(id = "uint16"))
# 5. Writing Data Frames (Compound Datasets)
df <- data.frame(
id = 1:5,
score = c(10.5, 9.2, 8.4, 7.1, 6.0),
grade = factor(c("A", "A", "B", "C", "D"))
)
h5_write(df, file, "records/scores", as = c(grade = "ascii[1]"))
# 6. Fixed-Length Strings
h5_write(c("A", "B"), file, "fixed_str", as = "ascii[10]")
# 7. Review the file structure
h5_str(file)
# 8. Clean up
unlink(file)
Run the code above in your browser using DataLab