Introduction To R Programming


R is most probably not a language that you would have learnt about in high school or college. This post will get you from absolute beginner to intermediate level in no time. So let’s get started!

Hello world and beyond!

Why Should You Adopt R Programming?

R Programming is the best mechanism for statistics, data analysis, and machine learning. It is more than a statistical package; it’s a programming language so that you can create your objects, functions, and packages

Here is how the hello world programme looks like in Python:

print (Hello World)

Simplistic and sleek, like all things should be!

Variables are declared using “<-” and follow certain conventions like:

  • Cannot start with symbol/numbers other than. (dot )
  • Only symbols allowed are .(dot) and  _ (underscore).
x<- "John Doe"

Looping In R

A simple for loop in R looks like this:

for (x in 1:15) {
  print(x)
}

The break function helps you to stop the loop once certain conditions are met:

languages<- list("haskell", "Ruby", "R" , "Python")

for (x in languages) {
  if (x == "R") {
    break
  }
  print(x)
}

The next statement helps you skip an element instead of elimating the loop:

languages<- list("haskell", "orange", "R" , "Python")

for (x in languages) {
  if (x == "orange") {
    next
  }
  print(x)
}

A simple while loop in R looks like this:

i <- 1
while (i < 6) {
  print(i)
  i <- i + 1
}

The next and break functions work similarly for while loops as well.

If-else ladder and operands

A typical if-else ladder in R looks like this:

a <- 544
b <- 33

if (b > a) {
  print("b is greater than a")
} else if (a == b) {
  print("a and b are equal")
} else {
  print("a is greater than b")
}

We can implement the AND(&) and OR (|) logical operators to make more complex programmes:

a <- 200
b <- 33
c <- 500

if (a > b & c > a){
  print("Both conditions are true")
}
a <- 200
b <- 33
c <- 500

if (a > b | a > c){
  print("At least one of the conditions is true")
}

You can make use of the following operators to implement different kinds of programmes using R: