R Tip: Avoid using T and F as synonyms for TRUE and FALSE

[This article was first published on Left Censored » R, 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.

By default when you start R, T and F are defined as TRUE and FALSE. When I review other people’s code, I often see functions defined with arguments set to these values by default. This is a very bad idea. T and F are symbols that can be redefined, so it shouldn’t be assumed that they will always evaluate to TRUE and FALSE. Making that assumption can introduce bugs to the code that are very hard to track down.

For example, imagine you have defined a function to sample from a vector after transforming the data in some way:

my_sample <- function(x, size, rep=F) {
    x <- x^2  # a simple transform
    sample(x, size, replace=rep)

When you just start R, my_sample will work as intended because F is FALSE:

> my_sample(1:10, 8)
 [1]   4   1   9 100  49  16  36  81

But if you call this function from inside another function, or after hours of hacking at the console, this may not be the case. For instance, what if at some point in your R session you redefined F <- 2:

> my_sample(1:10, 8)
 [1]   9  49 100   4  64  64  81  36

This type of bug can be very dangerous because they are very hard to replicate and, worse yet, you may never even notice you have them. Luckily, such bugs are easy to avoid: never use T and F as synonyms for TRUE and FALSE. It doesn’t take much more effort to type out TRUE and FALSE, but if you find it onerous, get an editor with tab-completion.


Via email, Ananda Mahto suggests adding the following bit of code to the top of your scripts to provide a warning when T and F have been redefined.

if (!identical(T, TRUE)) 
    stop("'T' has been remapped to '", T, "'")
if (!identical(F, FALSE)) 
    stop("'F' has been remapped to '", F, "'")

This doesn’t solve the problem, of course, but at least you get some warning.

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

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.

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)