I often write R code where I test the length of a vector, the number of rows in a data frame, or the dimensions of a matrix, for example if (length(myVector) == 1). While poking around in some base R code, I noticed that in such comparisons values are explicitly stated as integers, usually using the ‘L’ suffix, for example if (nrow(data.frame) == 5L). Explicit integers are also sometimes used for function arguments, for example these statements from the cor function: x <- matrix(x, ncol = 1L) and apply(u, 2L, rank, na.last = "keep"). When should integers be explicitly specified in R? Are there any potentially negative consequences from not specifying integers?
I often write R code where I test the length of a vector, the
Share
Using
1Letc is programmatically safe, as in it is explicit as to what is meant, and does not rely on any conversions etc.When writing code interactively, it can be easy to notice errors and fix along the way, however if you are writing a package (even base
R), it will be safer to be explicit.When you are considering equality, using floating point numbers will cause precision issues See this FAQ.
Explicitly specifying integers avoids this, as
nrowandlength, and the index arguments toapplyreturn or require integers.