Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R programming: Is it possible to declare return or parameter types of functions?

Tags:

function

types

r

Is it possible to declare the return type or the parameter types of functions in R?

For example, given the following function

probability_k_correct = function(k) {
    # ... calculate probability
    return (0.1 * k)
}

I'd like to make it obvious for the reader that k must be an integer, numeric, complex or some other type and that the function returns, for example, a numeric.

If it's not possible, are there any tools (like precompilers) that add this functionality?

like image 942
Alex R Avatar asked Nov 09 '19 17:11

Alex R


1 Answers

https://github.com/jimhester/types or https://cran.r-project.org/web/packages/types/

You can add type annotations to functions using the package below. These will be printed if you print the function closure, and are also supported with function tooltips in RStudio.

Annotated return types will not show up in the function auto-completion, but you can print the function closure to see them.

#devtools::install_github('jimhester/types')
# or install.packages("types")
library(types)

myadd <- function( x = ? numeric, y = ? numeric) {
  (x + y) ? numeric
}
myadd()


myadd2 <- function( x = ? numeric ? integer, y = ? numeric) {
  x + y
}

enter image description here

like image 122
smingerson Avatar answered Nov 15 '22 01:11

smingerson