Open In App

Creation and Execution of R File in R Studio

R Studio is an integrated development environment(IDE) for R. IDE is a GUI, where you can write your quotes, see the results and also see the variables that are generated during the course of programming. R is available as an Open Source software for Client as well as Server Versions.

Creating an R file

There are two ways to create an R file in R studio:



Once you open an R script file, this is how an R Studio with the script file open looks like.


So, 3 panels console, environment/history and file/plots panels are there. On top left you have a new window, which is now being opened as a script file. Now you are ready to write a script file or some program in R Studio.

Writing Scripts in an R File

Writing scripts to an R file is demonstrated here with an example:


In the above example, a variable ‘a’ is assigned with a value 11, in the first line of the code and there is b which is ‘a’ times 10, that is the second command. Here, the code is evaluating the value of a times 10 and assign the value to the b and the third statement, which is print(c(a, b)) means concatenates this a and b and print the result. So, this is how a script file is written in R. After writing a script file, there is a need to save this file before execution.



Saving an R File

Let us see, how to save the R file. From the file menu if you click the file tab you can either save or save as button. When you want to save the file if you click the save button, it will automatically save the file has untitled x. So, this x can be 1 or 2 depending upon how many R scripts you have already opened.


Or, it is a nice idea to use the Save as button, just below the Save one, so that, you can rename the script file according to your wish. Let us suppose we have clicked the Save as button. This will pop out a window like this, where you can rename the script file as test.R. Once you rename, then by clicking the save button you can save the script file.

So now, we have seen how to open an R script and how to write some code in the R script file and save the file.
The next task is to execute the R file.

Execution of an R file

There are several ways in which the execution of the commands that are available in the R file is done.

So, this is an example, where R file is executed, using the source with echo command.


It can be seen in the console, that it printed the command a = 11 and the command b = a*10 and also the output print(c(a, b)) with the values.
So, a is 11 and b is 11 times 10, this is 110. This is how the output will be printed in the console.
Values of a and b are also shown in the environment panel.

Run command over Source command:

Article Tags :