0

I'm currently using this handmade thing (which should of course be adjusted for different data types):


read_blob <- function(blob) {
  blob_con <- rawConnection(blob)
  data <- readBin(blob_con, "numeric", n = length(blob) / 4)
  close(blob_con)
  return(data)
}

write_blob <- function(data) {
  stopifnot(is.numeric(data))
  blob_con <- rawConnection(raw(0), "r+")
  writeBin(data, blob_con)
  blob <- rawConnectionValue(blob_con)
  close(blob_con)
  return(blob)
}

input_data <- c(123.45,234.56,345.67)

data_to_raw <- write_blob(input_data)
print(data_to_raw)

raw_to_data <- read_blob(data_to_raw)
print(raw_to_data)
stopifnot(all(input_data == raw_to_data))

I consider this somewhat of a workaround, having to open a rawConnection for reading and writing. Is there really no better way of doing this?

I know of

  • rawToChar but no other data types,
  • the package pack which should work with structure descriptors in the style of unpack('d*', data). I guess it was never finished because in my case only returns the first value regardless of what I put in the pattern, and last updated in 2008.
  • the package blob which doesn't seem to be doing this on its own.
meow
  • 925
  • 7
  • 22
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. What exactly are you passing in to these functions and what do you need them to return? – MrFlick Dec 21 '22 at 16:29
  • Thanks, I amended the example and it should now be clear what input/output data is expected – meow Dec 22 '22 at 11:31

0 Answers0