Programming with R – Returning Information as a List

November 2nd, 2010

In previous posts (here and here) we created a simple function that returns a single numeric value. In some situations it may be more useful to return a more flexible data type, such as a list object, to provide more information about the calculations that have been performed.


Fast Tube by Casper

We can extend our previous function by changing the return value to a list including the height and width supplied by the user. The last line of the function is changed to:

list(Height = height, Radius = radius, Volume = volume)

This creates a list with three elements, which are given very obvious names. The function in full is:

cylinder.volume.4 = function(height, radius)
{
    if (missing(height))
        stop("Need to specify height of cylinder for calculations.")
 
    if (missing(radius))
        stop("Need to specify radius of cylinder for calculations.")
 
    if (height < 0)
        stop("Negative height specified.")
 
    if (radius < 0)
        stop("Negative radius specified.")
 
    volume = pi * radius * radius * height
 
    list(Height = height, Radius = radius, Volume = volume)
}

We can call this function using a simple example:

> cylinder.volume.4(20, 4)
$Height
[1] 20
 
$Radius
[1] 4
 
$Volume
[1] 1005.310

The output from this function is a list with three slots as discussed above.

This approach is ideally suitable to statistical applications where we might have a model with a large amount of supplementary information that should be returned after it has been applied to a set of data.

Other useful resources are provided on the Supplementary Material page.

Comments are closed.