Type constraints and NAs in lambda.r

January 15, 2015
By

(This article was first published on Cartesian Faith » R, and kindly contributed to R-bloggers)

Someone asked recently how lambda.r deals with NAs in type constraints. Type constraints are optional decorations on a function that enforces the type for each function argument. The short answer is that since NAs are typed, they work just like other values.

Consider the toy function

f(x) %::% numeric : numeric
f(x) %as% x^2

Calling f with a vector containing NAs works as expected:

> f(c(1,2,3,NA,5))
[1]  1  4  9 NA 25

What happens if you pass a scalar NA? Now things get interesting.

> f(NA)
Error in UseFunction(f, "f", ...) : No valid function for 'f(logical)'

Lo, we get an error! This is an artifact of how R deals with NA values. Since NAs are typed, normally the type can be inferred by the other values in a vector. However, if NA is the only value i.e. a scalar, no information is available. Therefore R must choose some default value, which happens to be logical.

> class(NA)
[1] "logical"

To get around this situation, one can simply use the explicitly typed NA constant for the type you care about. In this case, it’s NA_integer_.

> f(NA_integer_)
[1] NA

See ?NA for more information on the mechanics and behavior of NA.

lambda.r is available on CRAN. The most recent version is on github and can be installed using devtools:

library(devtools)
install_github('lambda.r','zatonovo')

To leave a comment for the author, please follow the link and comment on their blog: Cartesian Faith » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, 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...

Comments are closed.

Search R-bloggers


Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)