自己编函数,最简单就是用新建程序脚本。写好你的程序,选择储存位置,注意在文件名后头一定要加".R"做后缀,不然R调用自己编写函数时是大不开的。
阶乘函数:
factorial=function(n){
prod(1:n)
}
(其实gamma(n+1)就能算n!)
例如把这个程序存在我的文档C:\Documents and Settings\lenovo\My Documents,文件名为factorial.R
下面编写一个求组合数的程序,其中调用这个阶乘函数:
mychoose=function(n,m){
source("C:\\Documents and Settings\\lenovo\\My Documents\\factotial.R")
factorial(n)/(factorial(m)*factorial(n-m))
}
反正我试了试是成功的:
> mychoose=function(n,m){
+ source("C:\\Documents and Settings\\lenovo\\My Documents\\factotial.R")
+ factorial(n)/(factorial(m)*factorial(n-m))
+ }
> mychoose(6,2)
[1] 15