rgms
rgms

Reputation: 129

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!

Upvotes: 3

Views: 260

Answers (2)

Ian Campbell
Ian Campbell

Reputation: 24888

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)

Upvotes: 2

alvaropr
alvaropr

Reputation: 799

I once faced a similar problem. After an API request I got a zipped binary file which I had to parse in the following way:

response.from.API.object
object.as.string.b64.binary = response.from.API.object$content
object.as.string.b64.dec = jsonlite::base64_dec(object.as.string.b64.binary)
base::writeBin(object.as.string.b64.dec, destination.fpath)

I think your zipped_r_object would be equivalent to my object.as.string.b64.binary

In my case I had to write the object to disk and then work from there.

Upvotes: 1

Related Questions