R编程:是否可以声明函数的返回类型或参数类型?

是否可以在R中声明函数的返回类型或参数类型?

例如,给定以下功能

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

我想让读者知道k必须是integernumericcomplex或其他某种类型,并且该函数返回,例如numeric

如果不可能,是否有任何工具(例如预编译器)添加此功能?

liulinjian123 回答:R编程:是否可以声明函数的返回类型或参数类型?

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

您可以使用下面的包在功能中添加类型注释。如果您打印功能闭包,这些将被打印,并且RStudio中的功能工具提示也支持这些功能。

带注释的返回类型将不会显示在函数自动完成中,但是您可以打印函数闭包以查看它们。

#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

本文链接:https://www.f2er.com/3131906.html

大家都在问