Skip to end of banner
Go to start of banner

Creating an R Package (Hello World Example)

Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 4 Next »

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("Sayonara")
Goodbye: Sayonara!

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 all the files in the package.
  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 contains information on the additional steps for creating the Package

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

  • No labels