Reading and Writing Data in R

If you are using an R console, you might want to import your data stored either in workspace Files or Database tables, do some analysis in R, and write your results to file. In this article, we will show you how to read and write data to and from R, as well as introduce some workspace-specific functions that you might find useful for working with files.

CSV files

CSV files stored in the workspace Files can easily be read and written from and to R console or script.

Reading CSV files

Reading CSV files from the Files folder:

dataset <- read.csv("~/files/your_folder/file_name.csv")
Writing CSV files

Writing CSV files to the Files folder:

write.csv(data, "~/files/your_folder/output_file_name.csv")

Database tables

You can import or export data tables stored in the workspace Database table tab either by using platform-specific functions (see 'Running XAP and R commands' below) or standard R libraries for interfacing with databases such as DBI or RPostgreSQL.

Importing database tables

The simplest way to import a database table is to use an XAP function:

dataset <- xap.read_table("dataset_name")

You can also read a workspace data table using the DBI library:

dataset <- dbReadTable(xap.conn, "dataset_name")

To list all the tables and database views in the current workspace, run:

xap.list_tables()

connect_db.gif

Writing to the Database table tab

The following XAP function writes a data frame to a table in the Database table tab. Note if a database table with that name already exists, the function will overwrite it:

xap.db.writeframe(dataset, "dataset_name")

Alternatively, you can use the DBI library to do this. If a table with that name already exists, the function will raise an error. However, if you do want to append to an existing data table, you can set append parameter to TRUE, or to overwrite a table, set overwrite to TRUE:

dbWriteTable(xap.conn, "dataset_name", dataset)

Running XAP and R commands

XAP is an R package for interfacing with the workspace from the R console. XAP includes functions for reading and writing to the Database table and Files tabs, creating PDFs, running SQL or R scripts.

You can display the full list of platform-specific functions by running:

ls("package:xaputils")

xap_functions.png

If you want to learn more about a specific XAP function, you can print out its documentation in the R console:

?xap.name_of_function

In the example below, we run a SQL script that queries a data table named sea_ice and computes the sea ice extent by region. The query output is then displayed in the console. Next, we run an R script that visualises the extent differences between the two locations. To display the visual output in the Plots tab, we set the print.eval parameter to TRUE.

sql_r.gif

Updated on October 16, 2023

Was this article helpful?