Site icon R-bloggers

Programming with R – Returning Information as a List

[This article was first published on Software for Exploratory Data Analysis and Statistical Modelling, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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 their blog: Software for Exploratory Data Analysis and Statistical Modelling.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.