Get packages that introduce unique syntax adopted less?
RI have this hypothesis that packages that introduce a unique syntax, or a workflow change, get adopted less by users, even if what these packages do is super useful. I’m going to discuss two examples of packages that I think are really, really useful, but sometimes I wonder how many R users use them, or would use them if they were aware these packages existed. I myself, only use one of them!
The first package is {typed}
which introduces a type
system for R. No more silent conversion to and from types without your knowing! If you don’t
know what a type system is, consider the following:
nchar("100000000")
## [1] 9
you get “9” back, no problem. But if you do:
nchar(100000000)
## [1] 5
You get 5 back… what in the Lord’s name happened here? What happened is that the number 100000000 could converted to a character implicitly. But because of all these 0’s, this is what happened:
as.character(100000000)
## [1] "1e+08"
It gets converted to a character alright, but scientific notation gets used! So yes,
1e+08 is 5 characters long… Ideally nchar()
would at least warn you that
this conversion is happening, or maybe even error. After all, it’s called nchar()
not nnumeric()
or
whatever. (Thanks to
@cararthompson
for this!)
A solution could be to write a wrapper around it:
nchar2 <- function(x, ...){
stopifnot("x is not a character" = is.character(x))
nchar(x, ...)
}
Now this function is safe:
nchar2(123456789)
## [1] Error in nchar2(123456789) : x is not a character
{typed}
makes things like this easier. Using {typed}
you can write the wrapper like this:
library(typed)
##
## Attaching package: 'typed'
## The following object is masked from 'package:utils':
##
## ?
strict_nchar <- ? function(x = ? Character(), ...){
nchar(x, ...)
}
{typed}
introduces ?
(masking the ?
command) allowing you to set the type the functions arguments
(x = ? Character()
) and also we had to write ?
in front of function
. It’s also possible to set
the return type:
strict_nchar <- Integer() ? function(x = ? Character(), ...){
nchar(x, ...)
}
strict_nchar("10000000")
## [1] 8
Hope you enjoyed! If you found this blog post useful, you might want to follow me on twitter for blog post updates and buy me an espresso or paypal.me, or buy my ebook on Leanpub. You can also watch my videos on youtube. So much content for you to consoom!