[This article was first published on R snippets, 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.
Standard sample function works differently when it gets single element integer vector as opposed to longer vectors. This can lead to unexpected bugs in R code.Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Several times I had a problem with code similar to one given here:
for (i in 1:4) {< o:p>
x <- i:4< o:p>
print(sample(x))< o:p>
}< o:p>
#[1] 4 1 2 3< o:p>
#[1] 3 2 4< o:p>
#[1] 4 3< o:p>
#[1] 3 2 1 4< o:p>
When looping over different integer vectors it is easy to forget that sample behaves differently when the vector is numeric and contains only one element.
A simple solution to this problem is given below. It guarantees consistent behavior of sampling:
for (i in 1:4) {< o:p>
x <- i:4< o:p>
print(x[sample(length(x))])< o:p>
}< o:p>
#[1] 4 1 2 3< o:p>
#[1] 3 2 4< o:p>
#[1] 3 4< o:p>
#[1] 4< o:p>
Considering this problem provoked me to think of other possibly unexpected properties of this function. Here is the sample code:
sample(4.3)< o:p>
#[1] 3 2 1 4< o:p>
sample(NA)< o:p>
#[1] NA< o:p>
sample(as.integer(NA))< o:p>
#Error in if (length(x) == 1L && is.numeric(x) && x >= 1) { : < o:p>
# missing value where TRUE/FALSE needed< o:p>
Firstly if sample receives a numeric (but not integer) vector with single element it truncates the argument and treats it as integer. This is not something that I would expect.
Secondly sample behaves differently when it is given NA argument of different modes and it produces error if this mode is numeric. Again this is not the expected behavior.
All these properties are worth remembering because they can lead to hard to track bugs in the code that do not show during standard testing.
To leave a comment for the author, please follow the link and comment on their blog: R snippets.
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.