如何保存每次调用向量的输出? 我见过类似的问题,但要么表述不当,要么针对更复杂的问题。看到最基本情况的解决方案对我很有帮助,我相信对其他初学者也很有帮助。
例如:
recursive = function(x) {
if (x < 1) {
print(x + 0.1)
return(recursive(x + 0.1))
}
}
recursive(0)
[1] 0.1
[1] 0.2
[1] 0.3
[1] 0.4
[1] 0.5
[1] 0.6
[1] 0.7
[1] 0.8
[1] 0.9
[1] 1
[1] 1.1
如何将这些输出直接编译为向量?
我尝试附加到一个空向量,但 R 不赞成这种方法。
output <- c()
recursive = function(x) {
if (x < 1) {
output <- append(output, x + 0.1)
print(x + 0.1)
return(recursive(x + 0.1))
}
}
recursive(0)
任何帮助将不胜感激!
最佳答案
您可以简单地连接输出。注意:谨慎使用<<-
.
recursive = function(x) {
if (x < 1) c(x, recursive(x + 0.1))
else x
}
recursive(0)
[1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 1.1
如果您需要显式使用return
函数,则不需要使用else
:
recursive1 <- function(x) {
if (x < 1) return(c(x, recursive1(x + 0.1)))
x
}
recursive1(0)
[1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 1.1
另一种方法是改变条件:
recursive2 <- function(x) {
if (x > 1) return(x)
c(x, Recall(x + 0.1))
}
recursive2(0)
[1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 1.1
关于R 中的递归函数 : How do I save the output of every call to a vector?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76276694/