Open In App

browser() Function in R

Last Updated : 21 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The browser method in R is used to simulate the inspection of the environment of the execution of the code. Where in the browser method invoked from. The browser method is also used to stop the execution of the expression and first carry out the inspection and then proceed with it. This results in the execution of the expression being paused for a while. This is then supplied to the interpreter and inspected first. 

This method is available in the base R Programming Language and has the following syntax

Syntax : browser(text, condition, expression)

Parameters:

  • text – A text string to be accessed.
  • condition – The condition to be accessed.
  • expression – In case of true the debugger is called otherwise the control return happens. The control is transferred back to the main program after hitting the Stop button.

For instance, in the following code snippet, str_fun is used to pass two parameters x and y to the calling method. The expression is the calculation of the final str given by fin_str is the submission of the two parameters x and y. Before the valuation of the expression, the browser method is called in order to debug the values of the parameters as well as the final result in case the value is found to be correct. Then the control is returned to the function back again. That is the evaluation of expression takes place and the final result is printed. The code output screens clearly indicate the right-hand side showing the values of all three variables x, y, and fin_str after the computation.

Using browse() in User-Defined Function 

R




#declaring a function to add two numbers x and y 
str_fun <- function(x, y) {      
  fin_str = x + y
  browser()                 
  fin_str = x + y
  print(fin_str)                        
}
  
#calling method
str_fun(x=2 , y=2)


Output:

browser() Function in R

 

Explanation:

The environment shows three variables, x = 2, y = 2, and fin_str = 4 respectively. In the code snippet below, the str_fun is an aggregate function, which is used to compute the maximum of the three numbers passed as arguments to this method. In the case of the computation of maximum, first, the browser method is invoked. It checks and then returns a result that is the highest of the input three numbers.

Concatenating Strings with browse() function

The following code snippet is used to concatenate strings using the in-built paste() method in R.

R




str_fun <- function(str1, str2) {    
  concat = paste(str1, str2, str1)
  browser()                
  fin_str = paste(str1, str2, str1)
  print(fin_str)                        
}
  
#calling method
str_fun(str1="Geeks", str2="For")


Output:

browser() Function in R

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads