简体   繁体   English

如何在R中编写递归函数?

[英]How can I write a recursive function in R?

How can I write a recursive function to obtain the combination(n,r)=combination(n-1,r-1)+combination(n-1,r) in R? 我如何编写一个递归函数来获取R中的combination(n,r)= combination(n-1,r-1)+ combination(n-1,r)? I tried the following code but I only get an error message: 我尝试了以下代码,但仅收到错误消息:

nCr=function(n, r) {
if (r == 0)
{
if (r == n) {

return (1)
} } else {
return (nCr(n-1, r-1) + nCr(n-1, r)) 
}
}

Thanks! 谢谢!

Related questions: one , two . 相关问题:

nCr <- function(n, r) {
  if (r == 0 | r == n) return (1)
  else return (nCr(n-1, r-1) + nCr(n-1, r)) 
}

nCr(20, 6)
[1] 38760
choose(20, 6)
[1] 38760

Note the performance of the built-in function. 注意内置功能的性能。

system.time(for(i in 1:10) nCr(20, 6))
##    user  system elapsed 
##    8.74    0.00    8.90 

system.time(for(i in 1:10) choose(20, 6))
##    user  system elapsed 
##       0       0       0 

The performance problems partly occur because the function is called with the same inputs many time. 出现性能问题的部分原因是多次调用相同的输入功能。 You can make nCr faster by caching the results ‐ this technique is useful for many recursive functions, though notice that the built-in function is still much faster. 您可以通过缓存结果来使nCr更快-此技术对许多递归函数很有用,尽管请注意,内置函数仍然要快得多。

library(memoise)
nCr2 <- memoise(nCr)
system.time(for(i in 1:10) nCr2(20, 6))
##    user  system elapsed 
##    0.88    0.00    0.91

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM