First R Program

First R Program

As a convention, our first R program will be the “Hello World!” program. We can run our R program either at R command prompt or we can use an R script file. Let’s see both one by one.

R command Prompt

To start your R program in Windows command prompt, just go to this path C:\Program Files\R\R-3.5.2\bin and type the R at your command prompt. Or you can set the environment variable.

This will start the R interpreter and you will get the prompt > where you can start typing your program.

First R Program1

 

 

 

Program:

Program to print “Hello World!” in the command prompt:

Here the first statement defines a string variable helloStr where we assign “Hello World!” and then next statement print() is being used to print the value stored in variable helloStr.

Output:

First R Program2

 

 

 

R Script File

We can also use script files to write our program and then execute this script file at your command prompt with the help of R interpreter called Rscript.

First of all, write the below code in a text file using any text editor like notepad and then save this file with the .R extension. Such as hello.R; if you do not set the environment variable, then you have to save this file in the bin folder of R.

Program:

To execute this script file use the following command at your command prompt. If you are using Linux or another operating system, the syntax will remain the same:

Output:

When we run the above command, it produces the following result:

First R Program3

RStudio

As we know RStudio is an open source IDE (Integrated Development Environment) for R programming language.

In RStudio, we can use the console to run command or we can also create a Script file.

To create a hello world program through the console of RStudio, just type the following line of code in the console:

The output will be:

First R Program 4

 

 

You can also create a script file in RStudio:

To create an R script file just go to the File -> New File -> R Script.

Now, you can see the R Script editor where you can type multiple lines of code and save your R program.

Copy the following code in your script file. And save it with .R extension.

Program:

To run this program press “Ctrl+A” to select all three lines of code and press “Ctrl +Enter”.

The output will be displayed at RStudio console.

First R Program 5

 

 

 

 

 

 

 

 

 

Note:-To clear the console of R or RStudio uses the following command:

Reference:
https://www.datamentor.io/r-programming/