Search code examples
rbinaryunzip

Unzip a R object straight from the environment


I have a R object (class: 'raw') loaded into the environment. It's in a binary format. I know this (zipped) R object contains a single file (e.g. a pdf or txt file).

Let's call this object: 'zipped_r_object'.

I do not have the original file saved on my computer. This object is fetched from a databaseconnection.

That is why I want to unzip the binary/raw 'zipped_r_object' directly from the R-environment and save the unzipped content in a new object ('unzipped_object'). This way, I can process the file further.

How can I do this in R? I know how to unzip from a saved zip-archive saved on my computer. But I can't seem to this exclusively in the R environment.

Many thanks!


Solution

  • One approach is to writeBin the object out to a file.

    writeBin(zipped_r_object, "temp.zip")
    

    You could also write it out to a temp file and then use unzip with list = TRUE to see the name of the file contained in the archive.

    temp <- tempfile()
    writeBin(zipped_r_object, temp)
    unzip(temp, list = TRUE)
    

    Then you could extract it to a temp directory:

    temp2 <- tempdir()
    unzip(temp, temp2)
    list.files(temp2)