DataScience Classroomnotes 21/Dec/2021

R-Functions

  • Hello-World Function:
hello_world <- function()
{
  print("Hello world")
}
hello_world()
  • Refer Here for the code
  • In the above code snippet we have created a function and assigned it to hello_world object and whenever we need to call the functionality we can call the function by hello_world()
  • Debugging the function:
  • Breakpoint => This will halt the execution and from here we can control the execution
  • Adding explicit function called as browser()
  • Now lets add a function with some arguments
say_hello <- function(name)
{
  sprintf("Hello %s", name)
}

say_hello('Khaja')
say_hello('Arundhati')

say_hello_again <- function(first, last)
{
  sprintf("Hello %s %s", first, last)
}
say_hello_again('Harish', 'Vanka')
say_hello_again(last = 'Sharma', first = 'Nikhil')
say_hello_again(last = 'Devella', 'Padmavathi')

  • Try Default Arguments: Default arguments will have some value assigned win the function defintion
say_hello_again <- function(first, last, middle="")
{
  sprintf("Hello %s %s %s", first, last, middle)
}

say_hello_again('pavan', 'gandhari')

say_hello_again('Ram', 'Reddy', 'M')
  • Extra Arguments: R offers a special operator that enables functions to take arbitrary number of arguments that do not need to be specified. This is the dot-dot-dot (…) argument
  • Exercise -> Find an approach to use the extra arguments passed
  person_info <- function(first, last, ...)
{
  print(ls())
  print(...)
}

person_info('test', 'test0')
  • To Proceed with Functions, we need to know more about control statements and iteration/looping constructs

R Operators

  • Arthimetic Operators:
  • + => Addition
  • - => subtraction
  • * => Multiplication
  • / => Division
  • ^ or ** => Exponent
  • %% => Modulus (Remainder)
  • %/% => Integer Division Preview
  • Comparision Operators:
  • == => Equals
  • != => Not equals
  • > => Greater than
  • < => Less than
  • <= => Less than or equals
  • >= => Greater than or equals Preview
  • Logical Operators:
  • & => Element wise logical and operator
  • && => Logical And operator
  • | => Element wise Logical OR operator
  • || => Logical or operator
  • ! => Logical Not
  • Miscellaneous Operators
  • : => creates a sequence
  • %in% => Findout if an element belongs to vector
  • %*% => Matrix Multiplication
  • Assignment operator <-

Control Statements

  • The if and else:
  • if syntax: if (expression) {
    <statmeents>
    }
  • if-else: if (expression) {
    <statmeents>
    }
    else {
    <statements>
    }
  • Refer Here for some samples
  • Activity:
  • Ensure you go through basic math concepts
    • prime numbers
    • fibonacci series
    • factorials

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About continuous learner

devops & cloud enthusiastic learner