How to write loop in R

How to write loop in R

Generally when we want to do same type of thing repeatedly then we use loop statement in different programming language. If you know other programming languages like C, C++, Java etc. it will be very much easy for you to understand. If you don’t know there is no problem. I’ll show you with example which make you understand about loop statement in R.

 

 

 

Example of combining repeat and for loop in r:

function_read_number <- function()
{
  r <- readline(prompt="Please, enter the value of n (0 for exit the loop):")
}

repeat
{
n <- as.integer(function_read_number());
if (n == 0)
{
print(“Thank you for using our program.You have successfully exited from the program…”);
break;
}
else
{
s<-0;
for(i in 1:n)
s<-s+i;
print(paste(“Summation of 1 to n:”, s))
}
}



																		
						
						
											

Add a Comment