Creating an R Package (Hello World Example)

Creating an R Package (Hello World Example)

Introduction

This document illustrates how to create an R package by using a simple "hello world" example. This simple package (helloWorld) contains two functions: hello(), which prints a hello message, and goodbye() which takes a single argument and prints a goodbye message plus the argument value.

Defining The Functions

The two functions can be defined using the following steps:

1) Open an R command prompt

2) Paste the following code into R:

hello <- function(){ cat("Hello World!\n") } goodbye <- function(message){ cat("Goodbye: ", message, "!\n", sep="") }

These functions should now be defined in your global namespace and can be executed just like any other function:

> hello() Hello World! > goodbye("Cruel World") Goodbye: Cruel World!

Creating the Package Skeleton

The function package.skeleton() can be used to create an R package from the objects in the workspace. To do this, you will need to call the function using two arguments:

  1. "name": This is the name of the package, "helloWorld" in this example. package.skeleton() will create a subdirectory in the current working directory with this name. This new directory will contain a file for each function in the package, as well as ???.

  2. "list": This is a character vector naming the R objects that should be put into the package, "hello" and "goodbye" in this example.

> package.skeleton(name="helloWorld", list=c("hello", "goodbye")) Creating directories ... Creating DESCRIPTION ... Creating Read-and-delete-me ... Saving functions and data ... Making help files ... Done. Further steps are described in './helloWorld/Read-and-delete-me'.

The "Read-and-delete-me" file is the high level guide for completing the documentation.  The files ending in *.Rd under helloWorld/man/ are 'self documenting', guiding the author through the documentation process.  The source code is placed in helloWorld/R/.  Fill in the package attributes in the helloWorld/DESCRIPTION file.

Note: There are other ways to create an R package using package.skeleton; see the function help file for details.

Additional Resources

Details on writing R packages can be found here: http://cran.r-project.org/doc/manuals/R-exts.pdf