Programming with R – Returning Information as a List

November 1, 2010
By

(This article was first published on Software for Exploratory Data Analysis and Statistical Modelling, and kindly contributed to R-bloggers)

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.

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.

To leave a comment for the author, please follow the link and comment on his blog: Software for Exploratory Data Analysis and Statistical Modelling.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: , ,

Comments are closed.