ChemSpider's API services offers the functionality to download image files of the chemicals. This functionality is implemented in the get_recordId_image() function. These image files can also be stored straight from R.

Installing the required magick package

Before downloading an example image for caffeine, the magick package needs to be installed.

install.packages("magick")

Downloading the PNG image of caffeine

First, the chemspiderapi package needs to be loaded and the API key needs to be retrieved.

library(chemspiderapi)

apikey <- keyring::key_get(service = "ChemSpider API key", username = Sys.getenv("USERNAME"))

Now, the "raw" image file (ChemSpider ID 2424) is downloaded using get_recordId_image().

caffeine_image_raw <- get_recordId_image(recordId = 2424L, apikey = apikey)

Next, the image needs to be read in using the magick::image_read() functionality.

library(magick)

caffeine_png <- image_read(caffeine_image_raw)

Viewing the image

The loaded image can be viewed by calling the object.

caffeine_png

Saving the PNG image

Saving the image is possible using the magick::image_write() function.

image_write(caffeine_png, path = "caffeine.png")


NIVANorge/chemspiderapi documentation built on Jan. 10, 2021, 10:12 a.m.