Functional looping in R



I am attempting this simple problem of solving f(x)=x^2 - 2*x - 2 = 0 by using Newton Raphson method and hence counting the number of iterations(it) required. {using looping by function recurssion}

NR <- function(x) {
 f <- x^2-2*x-2
 fd<- 2*x-2
 x1<- x -f/fd
 f1 <- x1^2-2*x1-2
 it<- it+1
print("The solution by NR method is :")
print("The number of iterations are :")

I am getting the correct solution for x but the iteration is not incrementing even though it is declared as global.Please share if any conceptual mistake I am doing in using the object declaration.


Hi @Abhay01,

There is a small error in the code. Basically, when you iterate the value of ‘it’ in the function NR, it generates a local variable ‘it’ and iterates it instead. To iterate the global variable use the following code :

it<<- it+1

This will iterate the global variable. Rest of the logic is fine. It will give you the correct result.



Hi @shashwat.2014,

Thankyou for correction.It works.

Though one would expect R to give warning or error of “object not found” in such cases.



R will not generate an error in this instance because in the first iteration, the within function value of it is set to the value from the parent environment + 1. Therefore, no error is generated. Once the local value is instantiated, it is used for subsequent iterations of the loop. This is consistent with R’s pattern for resolving object names: start with the child environment, then move up the environment chain until the global environment is reached.

> it <- 1
> testFunction <- function() {
+      for (i in 1:5) {
+           it <- it + 1
+           message(paste("value of it is:",it))
+      }
+ }
> testFunction()
 value of it is: 2
 value of it is: 3
 value of it is: 4
 value of it is: 5
 value of it is: 6
> it
[1] 1




Thankyou. :slight_smile: nicely explained.