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 Datasets, 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")

Datasets

You can import or export data tables stored in the workspace Datasets 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 datasets

The simplest way to import a dataset 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()

Writing to the Datasets tab

The following XAP function writes a data frame to a table in the Datasets tab. Note if a dataset 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 dataset, 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 Datasets 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")

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 an 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.

Updated on June 18, 2021

Was this article helpful?

Related Articles

Not the solution you were looking for?
Click the link below to submit a support ticket
CONTACT SERVICE DESK