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

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.

### Update

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.

This entry was posted in Hacking, R, Tip. Bookmark the permalink.