# Programming with R – Checking Data Types

November 13, 2010
By

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

There are a number of useful functions in R that test the variable type or convert between different variable types. These can be used to validate function input to ensure that sensible answers are returned from a function or to ensure that the function doesn’t fail.

Following on from a previous post on a simple function to calculate the volume of a cylinder we can include a test with the is.numeric function. The usage of this function is best shown with a couple of examples:

> is.numeric(6) [1] TRUE > is.numeric("test") [1] FALSE

The function returns either TRUE or FALSE depending on whether the value is numeric. If a vector is specified to this function then a vector or TRUE and FALSE elements is returned.

We can add two statements to our volume calculation function to test that the height and radius specified by the user are indeed numeric values:

 if (!is.numeric(height)) stop("Height should be numeric.")   if (!is.numeric(radius)) stop("Radius should be numeric.")

We add these tests after checking whether the height and radius have been specified and before the test for whether they are positive values. The function now becomes:

cylinder.volume.5 = 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 (!is.numeric(height)) stop("Height should be numeric.")   if (!is.numeric(radius)) stop("Radius should be numeric.")   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) }

A couple of examples show that the function works as expected:

> cylinder.volume.5(20, 4) $Height [1] 20$Radius [1] 4   \$Volume [1] 1005.310   > cylinder.volume.5(20, "a") Error in cylinder.volume.5(20, "a") : Radius should be numeric.

These various validation checks can be combined in different ways to ensure that a user does not try to use a function in a way that was not intended and should lead to greater confidence in the output from the function. This is one approach to checking function arguments and there are likely other slicker ways of doing things.

Other useful resources are provided on the Supplementary Material page.

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...