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

问题描述 投票:1回答:1

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

例如,具有以下功能

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

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

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

r function types
1个回答
3
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.