Accessing Cloudant from RStudio

The sofa package is a great way to interact between R and Cloudant (or any CouchDB data store for that matter).

Below is a quick example of how to read and write information to and from your Bluemix Cloudant data store and your R session in DSX RStudio:

#install the package if it is isn't already installed.
#install.packages("sofa")
#load the package:
library('sofa')
#ENTER YOUR USERNAME AND PASSWORD:
YOUR_USERNAME = ENTER_USER_NAME
YOUR_PASSWORD = ENTER_PASSWORD
#Create a connection
conn <- Cushion$new(
host = paste0(YOUR_USERNAME,".cloudant.com"),
port = 443,
transport = 'https',
user = YOUR_USERNAME,
pwd = YOUR_PASSWORD
)
#ping the server to make sure that all is well
ping(conn)
#list your databases
db_list(conn)
#list of all dbs and print to screen:
dbs = db_list(conn)
#list of docs in a db (of course be careful if your db is large):
db_docs = db_alldocs(conn, dbname= dbs[1])
#create a database:
db_create(conn, dbname='leothelion')
#make a simple doc
doc1 <- '{"name": "drink", "beer": "IPA", "score": 5}'
#upload doc to the database
doc_create(conn, dbname="leothelion", doc1, docid="abeer")
#grab the doc back
doc_get(conn, dbname='leothelion',docid="abeer")

You can get your Bluemix Cloudant credentials by drilling down into your Cloudant service in Bluemix and then click into the Service credentials tab. You may have to create new credentials if you do not already have them.

See https://github.com/ropensci/sofa for many other features in the sofa package for accessing and managing your CouchDB instances.

NOTE: You can only access Cloudant from R using DSX RStudio at this time. We are working a solution for DSX Notebooks.


Originally published at datascience.ibm.com on May 5, 2017 by Jim Crozier.