我有一个测试DF:在一个递归函数检测无限循环(R)
testdf<-data.frame(x = seq(1,10), y= c(1, 1, 4, 3, 2, 6, 7, 4, 9, 10))
testdf
x y
1 1 1
2 2 1
3 3 4
4 4 3
5 5 2
6 6 6
7 7 7
8 8 4
9 9 9
10 10 10
我想要写,其输入行号和“跟随”的函数的y值,直到它找到一个行对于哪个列x =列y。
get_acc_x<-function(rownum){
if(testdf[rownum, 'x'] == testdf[rownum, 'y']){
return(rownum)
}else{
get_acc_x(testdf[rownum, 'y'])
}
}
所以,运行get_acc_x(1)返回1,get_acc_x(9)返回图9,get_acc_x(2)返回1,get_acc_x(5)也将返回1等
但是,如果我要在数字8上运行此函数,它将进入无限循环,在3和4之间来回切换。在这种情况下检测无限循环的最简单方法是什么?我想跟踪过去的输入,所以如果多次使用相同的输入,我可以停止该功能,但我不知道如何最好地跟踪输入。