How to write the first program in the R programming language

Learn R Programming- Simple Guide

R is a programming language as well as environment commonly used in statistical computing, data analytics, as well as scientific research.
It is one of the most popular languages used by statisticians, data analysts, researchers as well as marketers to retrieve, clean, analyze, visualize as well as present data.
Due to its expressive syntax as well as an easy-to-use interface, it has grown in popularity in recent years.

Why should we use R for statistical computing and graphics?

R is open source as well as free!
R is free to download as it is licensed under the terms of GNU General Public license.
There’s more, most R packages are available under the same license so you can use them, even in commercial applications without having to call your lawyer.

R is having an increased popularity every year

IEEE publishes a list of the most popular programming languages each year.
R was ranked 5th in 2016, up from 6th in 2015.
It is a big deal for a domain-specific language like R to be more popular than a general purpose language like C++.
This not only shows the increasing interest in R as a programming language but also of the fields like Data Science as well as Machine Learning where R is commonly used.

Platforms on which R runs

You can find distributions of R for all popular platforms like:

  • Windows,
  • Linux,
  • Mac

R code that you write on one platform can easily be ported to another without any issues.
Cross-platform interoperability is an important feature to have in today’s computing world even Microsoft is making its envy.
NET platform available on all platforms after realizing the benefits of technology that runs on all systems.

Learning R will prove to be benefitted for you as it will increase your chances of being hired in big companies

Data scientists are paid a median of $98,000 worldwide.
The figure is higher in the US – around $144,000.
Of course, knowing how to write R programs won’t get you a job straight away, a data scientist has to juggle a lot of tools to do their work.
Even if you are applying for a software developer position, R programming experience can make you stand out from the crowd.

Who uses R?

R is being used by the biggest tech giants.
Adoption by tech giants is always a sign of a programming language’s potential.
Today’s companies don’t make their decisions on a whim.
Every major decision has to be backed by concrete analysis of data.

Companies Using R

R is the right mix of simplicity as well as power, as well as companies all over the world use it to make calculated decisions.

Run R Programming on Your Computer

Find the easiest way to run R programming on your system

To run R programming

  • Go to the official site of R Programming
  • Click on the CRAN link on the left sidebar
  • Select a mirror
  • Click “Download R for OS X”
  • Download the latest pkg binary
  • Run the file and follow the steps in the instructions to install R.

Your First R Program

R holds a reputation for getting things done with very little code.
If you’re a programmer as well as thinking “Here comes the Hello World code”, you’re in for a surprise.
In just three lines of code, your first R program will generate 10,000 numbers in a random distribution, organize them based on the frequency as well as create a fancy bar chart.
Copy the following code into the RStudio window, press Ctrl+A(Windows) or Cmd+A(Mac) to select all three lines as well as press Ctrl+Enter(Windows) or Cmd+Enter(Mac)

n <- floor(rnorm(10000, 500, 100))

t <- table(n)

barplot(t)

Look at the right bottom section of RStudio and you will see this beautiful bar graph showing the bell curve of a random normal distribution.

Here’s what each part of the code does:

Getting a list of random numbers in normal distribution

n <- floor(rnorm(10000, 500, 100))

The first line generates a list of 10000 random numbers in a normal distribution such that the mean of these numbers is 500 as well as standard deviation 100.

The floor function takes each number in this list as well as removes the decimal point.

You can even try running this code separately in the R console as well as see the output as:

Counting occurrences of each value.
The table function takes these 10000 numbers as well as counts the frequency of each

Since it is a normal distribution, you can clearly see the frequencies of the numbers gradually increase as we approach the mean.

Plotting the frequencies on a bar graph

The barplot function takes this table of frequencies as well as creates the bar chart out of the data.

We don’t really need three lines. In just one line, we could have done the same thing in one line while adding labels to the x as well as y-axes with

barplot(table(floor(rnorm(10000, 500, 100))), xlab=”Numbers”, ylab=”Frequencies”)

This is the power of the R programming language.
As a tool specifically built for statisticians, it performs all common operations using an expressive syntax that you will learn to love.

How Codersera has helped in making people learn R programming?

R is a programming language about which not much people are aware of.
People don’t have any knowledge about R programs.
Codersera has taken this initiative of making people aware of these rare programming languages and make an effort in making them learn about how it works.
Have a look here.

Getting Started With R console

Here, While RStudio is an amazing tool to get started learning R, it is only an interface to the R console.
It is important to be familiar with running R programs directly through the command prompt or terminal because you might not always have access to a graphical interface if you are running R programs on a server.

Hence, If R is installed correctly, you can open the R console by typing ‘R’ on the terminal and pressing Return/Enter.

When you start R, the first thing you will see is the R console with the default “>” prompt.
We can start typing commands directly at the prompt and hit return to execute it.

For instance, try typing the following commands on the R prompt

> n <- c(2, 3, 5, 10, 14)

> mean(n)

[1] 6.8

As you can see, each command is executed as soon as you press the return key and if there is any output then it is displayed.

If the command is incomplete when you hit return, the prompt changes to “+” as well as continue to take input until the command is syntactically complete.

Alternatively, we can execute R commands stored in an external file using the function source() as follows.

> source(“example.R “)

To exit the command prompt we can call the q() function (as in quit).

> q()

Different ways to run R scripts

Sometimes you may need to run an R program inside a batch or shell script.
There are different ways to achieve that.

Method 1: Using R CMD BATCH command

Save your R script in a text file with .R extension as well as type the following command.

R CMD BATCH /home/demo/learnR/Rprogramming.R

The output of this command will be stored in a file called Rprogramming.Rout

Method 2: Using Rscript

Use the following command

Rscript /home/demo/learnR/Rprogramming.R

The difference between R CMD and Rscript is that Rscript prints the output to STDOUT instead of a file.

If you want to turn your R program into an executable, you can specify that you want the file to run using Rscript by adding the following line at the beginning of your R script.

#!/usr/bin/env Rscript

For example, If your R program looks like

#!/usr/bin/env Rscript

n <- c(2, 3, 5, 10, 14)

mean(n)

You can directly execute it from the terminal as ./Rprogramming.R

R Programming Examples

Some Examples on basic concepts of R programming.

We have provided working source code on all these examples listed below.
However, we recommend you to write code on your own before you check them.
Because learning by trying is the best way to learn any programming language including R.

R Program to Check Prime Number

Example to check whether an integer entered by the user is a prime number or not using control statements.

To understand this example, you should have the knowledge of following R Programming topics:

R if…else Statement
R for Loop
R break and next statement
R Operators

A positive integer greater than 1 which has no other factors except 1 as well as the number itself is called a prime number.

Numbers 2, 3, 5, 7, 11, 13 etc. are prime numbers as they do not have any other factors.

But, 6 is not prime (it is composite) since, 2 x 3 = 6.

Example: Check Prime Number

# Program to check if the input number is prime or not

# take input from the user

num = as.integer(readline(prompt=”Enter a number: “))

flag = 0

# prime numbers are greater than 1

if(num > 1) {

# check for factors

flag = 1

for(i in 2:(num-1)) {

if ((num %% i) == 0) {

flag = 0

break

}

}

}

if(num == 2)    flag = 1

if(flag == 1) {

print(paste(num,”is a prime number”))

} else {

print(paste(num,”is not a prime number”))

}

Output 1

Enter a number: 25

[1] “25 is not a prime number”

Output 2

Enter a number: 19

[1] “19 is a prime number”

Here, we take an integer from the user as well as check whether it is prime or not. Numbers less than or equal to 1 are not prime numbers.

Hence, we only proceed if the num is greater than 1.
We check if num is exactly divisible by any number from 2 to num – 1.

If we find a factor in that range, the number is not prime.
Else the number is prime.

We can decrease the range of numbers where we look for factors.

In the above program, our search range is from 2 to num – 1.

We could have used the range, [2, num / 2] or [2, num ** 0.5].
The later range is based on the fact that a composite number must have a factor less than the square root of that number.
Otherwise, the number is prime.

R Program to Find the Factorial of a Number

In this example, you’ll learn to find the factorial of a number without using a recursive function.

To understand this example, you should have the knowledge of following R programming topics:

R if… else Statement
R for loop

The factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
Factorial is not defined for negative numbers and the factorial of zero is one, 0! = 1.
This example finds the factorial of a number normally. However, you can find it using recursion as well.

Example: Find the factorial of a number

# take input from the user

num = as.integer(readline(prompt=”Enter a number: “))

factorial = 1

# check is the number is negative, positive or zero

if(num < 0) {

print(“Sorry, factorial does not exist for negative numbers”)

} else if(num == 0) {

print(“The factorial of 0 is 1”)

} else {

for(i in 1:num) {

factorial = factorial * i

}

print(paste(“The factorial of”, num ,”is”,factorial))

}

Output

Enter a number: 8

[1] “The factorial of 8 is 40320”

Here, we take input from the user and check if the number is negative, zero or positive using if…else statement.

If the number is positive, we use for loop to calculate the factorial.

We can also use the built-in function factorial() for this.

> factorial(8)

[1] 40320

If you have any queries or if you want to hire good freelancers, Click here:

Leave a Comment

Your email address will not be published. Required fields are marked *