Dr.
SNSRAJALAKSHMI
        COLLEGE OFARTSANDSCIENCE
                        (AUTONOMOUS)
            Accredited by NAAC (Cycle – III) with ‘A+’
          Grade(Recognised by UGC, Approved by AICTE,
          New DelhiandAffiliated toBharathiarUniversity)
                       Coimbatore –641049.
            Reg No:
        Certified that this is bonafide record of work done
       byMr./Ms.
                   Core Laboratory – 1:21PCC301– IT
     APPLICATIONS (R PROGRAMMING)
                                  1.
                                  2.
SIGNATUREOFTHE HoD                 SIGNATUREOFSTAFFIN-CHARGE
                Submitted for M.Com (CA) Degree I
         semesterPracticalExaminationheldon
INTERNALEXAMINER                           EXTERNALEXAMINER
                                 TABLEOFCONTENTS
                          IT APPLICATIONS (R-PROGRAMMING)
Sl.                                                                           PAGE
      DATE                              TITLE                                        SIGNATURE
NO                                                                             NO
1            1. Using Class function check the type of data contained in a
             variable.
             2. Usingncharfunctions find the length of a character.
2            Construct a basic data. Frame,
             1. Assign the column names and row names of a data frame.
             2. Using head function print out the first few rows.
             3. Access entire row while not specifying any column.
             4. Access entire column while not specifying any row.
             5. Create a set of indicators variable using model matrix.
3            Create an element list - Single, Two, Three, Empty list.
             Access an individual element of a list and Append elements
             to a list.
4            Create matrix Using R function.
5            Create Arrays Using R function.
6            Read data from a csv file and database
7            Create an RData files.
8            Present simple graphs using base graphics and basic
             ggplot2.
9            Using R build a function using Arguments.
10           Write a function using if and else, Switch, logical and or
             operation.
11           Write a function that using for loop, while loops, controlling
             loop.
12           Write a function using apply, 1apply, sapply, mapply and
             aggregate.
 IT APPLICATIONS
(R-PROGRAMMING)
PROGRAM1                                                    DATE:
1. USING CLASS FUNCTION CHECK THE TYPE OF DATA CONTAINED
                       IN A VARIABLE.
2. USING NCHAR FUNCTIONS FIND THE LENGTH OF A CHARACTER.
____________________________________________________________________________
AIM:
ALGORITHM:
 CODING:
 1. USING CLASS FUNCTION CHECK THE TYPE OF DATA CONTAINED
 IN A VARIABLE.
          a = c(1, 2, 5, 3, 4, 0, -1, -3)
          b = c("Red", "Green", "White")
          c = c(TRUE, TRUE, TRUE, FALSE, TRUE, FALSE)
          print(a)
          print(typeof(a))
          print(b)
          print(typeof(b))
          print(c)
          print(typeof(c))
OUTPUT:
          [1] 1 2 5 3 4 0 -1 -3
          [1] "double"
          [1] "Red" "Green" "White"
          [1] "character"
          [1] TRUETRUETRUE FALSE TRUE FALSE
          [1] "logical"
CODING:
2. USING NCHAR FUNCTIONS FIND THE LENGTH OF A CHARACTER
(FIBONACCI)
          Fibonacci <- numeric(10)
          Fibonacci[1] <- Fibonacci[2] <- 1
          for (i in 3:10) Fibonacci[i] <- Fibonacci[i - 2] + Fibonacci[i - 1]
          print("First 10 Fibonacci numbers:")
          print(Fibonacci)
OUTPUT:
          [1] "First 10 Fibonacci numbers:"
          [1] 1 1 2 3 5 8 13 21 34 55
 PROGRAM2                                           DATE:
                 CONSTRUCT A BASIC DATA. FRAME,
1. ASSIGN THE COLUMN NAMES AND ROW NAMES OF A DATA FRAME.
2. USING HEAD FUNCTION PRINT OUT THE FIRST FEW ROWS.
3. ACCESS ENTIRE ROW WHILE NOT SPECIFYING ANY COLUMN.
4. ACCESS ENTIRE COLUMN WHILE NOT SPECIFYING ANY ROW.
5. CREATE A SET OF INDICATORS VARIABLE USING MODEL MATRIX
 ____________________________________________________________________
 AIM:
 ALGORITHM:
   CODING:
1. CREATING DATAFRAME FROM GIVEN 4 VECTORS.
           # creating a vector with some value
           id = c(1, 2, 3)
           # creating another vector with some value
           name = c("karthik" , "nikhil" , "sravan")
           # creating another vector with some value
           branch = c("IT" , "CSE" , "IT")
           # creating another vector with some value.
           favourite_subject = c("SE" ,"DAA" , "OS")
           # passing the vectors into data.frame() function
           # as parameters
           df1=data.frame(id, name, branch, favourite_subject)
           # printing the data frame.
           print(df1)
OUTPUT
CREATED VECTOR WITH 5 CHARACTERS
             columns= c("id","names","address","phone","aadhar no")
             # pass this vector length to ncol parameter
             # andnrow with 1
             myData = data.frame(matrix(nrow=1, ncol = length(columns)))
             # assign column names
             colnames(myData) = columns
             # display
             print(myData)
             # pass this vector length to ncol parameter and
             # nrow with 6
             myData = data.frame(matrix(nrow=6, ncol = length(columns)))
             # assign column names
             colnames(myData) = columns
             # display
             print(myData)
OUTPUT:
          id names address phone aadhar no
          1 NA NANANANA
          id names address phone aadhar no
          1 NA NANANANA
          2 NA NANANANA
          3 NA NANANANA
          4 NA NANANANA
          5 NA NANANANA
          6 NA NANANANA
  INSERT MULTIPLE ROWS IN R DATAFRAME
          # creating another data frame
          df2 = data.frame(num = c( 4 : 6),
          branch = c("EEE", "Mechanical", "civil"))
          # selecting 1-2 rows , all columns from df1
          new_row = df2[c(1, 2, 3),]
          # we can access data from a data frame through indexing .
          # since it is a 2 dimensional one we can access data
          # by row number and column number .
          # here c(1,2,3) represents row numbers and we left column
          # numbers as empty . then all columns are accessed .
          # new_row is appended to the df1
          df1 = rbind(df1, new_row)
          #printing updated data frame
          print(df1)
OUTPUT:
PROGRAM3                                                   DATE:
   CREATE AN ELEMENT LIST - SINGLE, TWO, THREE, EMPTY LIST.
         ACCESS AN INDIVIDUAL ELEMENT OF A LIST.
                APPEND ELEMENTS TO A LIST.
_______________________________________________________________________________
AIM:
ALGORITHM:
  CODING:
CREATING A LIST
          # vector with names
          names=c("bobby","pinkey","rohith","gnanu")
          # vector with marks
          marks=c(78,90,100,100)
          # address vector
          address=c("kakumanu","hyd","hyd","hyd")
          # pass these vectors as inputs to the list
          # address vector
          student=list(names,marks,address)
          print(student)
OUTPUT:
APPENDING DATA TO THE LIST
         # vector with names
         names=c("bobby","pinkey","rohith","gnanu")
         # vector with marks
         marks=c(78,90,100,100)
         # address vector
         address=c("kakumanu","hyd","hyd","hyd")
         # college values
         college=c("vignan","vignan","vignan","vignan")
         # pass these vectors as inputs to the list
         student1=list(student1_names=names,student1_marks=marks,
         student1_address=address,student1_college=college)
         # vector with names
         names=c("ravi","devi","siree","priyank")
         # vector with marks
         marks=c(78,90,100,100)
         # address vector
         address=c("hyd","hyd","hyd","hyd")
         # college values
         college=c("vvit","vvit","vvit","vvit")
         # pass these vectors as inputs to the list
         # address vector
         student2=list(student2_names=names,student2_marks=marks,
         student2_address=address,student2_college=college)
         # append list 1 and list 2
         print(append(student1,student2))
OUTPUT:
PROGRAM4                                           DATE:
               CREATE MATRIX USING R FUNCTION
____________________________________________________________________
AIM:
ALGORITHM:
CODING:
CREATE A BLANK MATRIX
          m = matrix(, nrow = 10, ncol = 5)
          print("Empty matrix of 10 rows and 5 columns:")
          print(m)
OUTPUT:
          [1] "Empty matrix of 10 rows and 5 columns:"
               [,1] [,2] [,3] [,4] [,5]
           [1,] NA NANANANA
           [2,] NA NANANANA
           [3,] NA NANANANA
           [4,] NA NANANANA
           [5,] NA NANANANA
           [6,] NA NANANANA
           [7,] NA NANANANA
           [8,] NA NANANANA
           [9,] NA NANANANA
          [10,] NA NANANANA
CODING:
CREATE A MATRIX TAKING A GIVEN VECTOR OF NUMBERS AS INPUT.
DISPLAY THE MATRIX.
          M = matrix(c(1:16), nrow = 4, byrow = TRUE)
          print("Original Matrix:")
          print(M)
OUTPUT:
          [1] "Original Matrix:"
             [,1] [,2] [,3] [,4]
          [1,] 1 2 3 4
          [2,] 5 6 7 8
          [3,] 9 10 11 12
          [4,] 13 14 15 16
PROGRAM5                                                    DATE:
                  CREATE ARRAYS USING R FUNCTION.
_______________________________________________________________________________
AIM:
ALGORITHM:
 CODING:
1 DIMENSIONAL ARRAY
          m=matrix(1:12,3,4)
          print("Original matrix:")
          print(m)
          a = as.vector(m)
          print("1 dimensional array:")
          print(a)
OUTPUT:
          [1] "Original matrix:"
             [,1] [,2] [,3] [,4]
          [1,] 1 4 7 10
          [2,] 2 5 8 11
          [3,] 3 6 9 12
          [1] "1 dimensional array:"
           [1] 1 2 3 4 5 6 7 8 9 10 11 12
2 DIMENSIONAL ARRAY
          print("Two vectors of different lengths:")
          v1 = c(1,3,4,5)
          v2 = c(10,11,12,13,14,15)
          print(v1)
          print(v2)
          result = array(c(v1,v2),dim = c(3,3,2))
          print("New array:")
          print(result)
OUTPUT:
          [1] "Two vectors of different lengths:"
          [1] 1 3 4 5
          [1] 10 11 12 13 14 15
          [1] "New array:"
          ,,1
             [,1] [,2] [,3]
          [1,] 1 5 12
          [2,] 3 10 13
          [3,] 4 11 14
          ,,2
             [,1] [,2] [,3]
          [1,] 15 4 11
          [2,] 1 5 12
          [3,] 3 10 13
3 DIMENSIONAL ARRAY
          v = sample(1:5,24,replace = TRUE)
          dim(v) = c(3,2,4)
          print("3-dimension array:")
          print(v)
OUTPUT:
          [1] "3-dimension array:"
          ,,1
             [,1] [,2]
          [1,] 4 2
          [2,] 4 2
          [3,] 2 1
          ,,2
             [,1] [,2]
          [1,] 4 2
          [2,] 2 4
          [3,] 2 4
          ,,3
             [,1] [,2]
          [1,] 4 2
          [2,] 1 5
          [3,] 3 2
          ,,4
             [,1] [,2]
          [1,] 3 3
          [2,] 1 5
          [3,] 1 2
PROGRAM6                                                    DATE:
            READ DATA FROM A CSV FILE AND DATABASE.
_______________________________________________________________________________
AIM:
ALGORITHM:
CODING:
STEP 1: SET OR CHANGE THE WORKING DIRECTORY
         # gives the current working directory
         getwd()
        # changes the location
        setwd("C:/Users/Vanshi/Desktop/gfg")
OUTPUT:
        C:/Users/Vanshi/Documents
STEP 2: READ THE CSV FILE
        sdata<- read.csv("SampleData.csv", header = TRUE, sep = ",")
        sdata
        # views the data frame formed from the csv file
        View(sdata)
OUTPUT:
PROGRAM7                                                    DATE:
                        CREATE AN R-DATA FILES.
_______________________________________________________________________________
AIM:
ALGORITHM:
CODING:
Step 1: Using the save() function to save the file in.RData format
         gfg_data = data.frame(A = c(7,6,2,8,1),
         B = c(4,2,9,7,3),
         C = c(1,7,2,6,8))
         print("Dataframe:->")
         print(gfg_data)
         save(gfg_data, file = "gfg.RData")
OUTPUT:
STEP 2: USING THE LOAD() FUNCTION TO LOAD THAT SAVED.RDATA FILE
         gfg_data= data.frame(A=c(7,6,2,8,1),
         B=c(4,2,9,7,3),
         C=c(1,7,2,6,8))
         print("Dataframe:->")
         print(gfg_data)
         save(gfg_data,file="gfg.RData")
         load("gfg.RData")
STEP3: USING FILE.INFO() FUNCTION TO GET THE INFORMATION OF A
PARTICULAR FILE.
        gfg_data= data.frame(A=c(7,6,2,8,1),
        B=c(4,2,9,7,3),
        C=c(1,7,2,6,8))
        print ("Dataframe:->")
        print(gfg_data)
        save(gfg_data,file="gfg.RData")
        load("gfg.RData")
        file.info("gfg.RData")
OUTPUT:
 PROGRAM8                                     DATE:
       PRESENT SIMPLE GRAPHS USING BASE GRAPHICS AND BASIC
                            GGPLOT2.
  __________________________________________________________
AIM:
 ALGORITHM:
  CODING:
  COMPARING GGPLOT2 AND R BASE GRAPHICS(Bar Chart)
#Define a data vector
data = c(1,3,6,4,9)
#bar plot the vector -- simple plot with no legends and colors
barplot(height=data, main="Cancer-data", xlab="Days", ylab="Response
Index",names.arg=c("grp-1","grp-2","grp-3","grp-4","grp-5"),border="blue",
density=c(10,20,30,40,50))
  OUTPUT:
BASE GRAPHICS
      par(las=1)
      barplot(dat$total_bill,
      names.arg=dat$time,
      col="#AFC0CB",
      border=FALSE,
      main="Average Bill for Two-Person Meal")
OUTPUT:
PROGRAM9                                           DATE:
         USING R BUILD A FUNCTION USING ARGUMENTS.
____________________________________________________________________
AIM:
ALGORITHM:
  CODING:
ADDING ARGUMENTS IN R
          # Function definition
          # To check n is divisible by 5 or not
          divisbleBy5 <- function(n){
          if(n %% 5 == 0)
          {
                 return("number is divisible by 5")
          }
          else
          {
                 return("number is not divisible by 5")
          }
          }
          # Function call
          divisbleBy5(100)
          divisbleBy5(4)
          divisbleBy5(20.0)
OUTPUT:
          [1] "number is divisible by 5"
          [1] "number is not divisible by 5"
          [1] "number is divisible by 5"
ADDING MULTIPLE ARGUMENTS IN R
          # Function definition
          # To check a is divisible by b or not
          divisible<- function(a, b){
          if(a %% b == 0)
          {
                  return(paste(a, "is divisible by", b))
          }
          else
          {
                  return(paste(a, "is not divisible by", b))
          }
          }
          # Function call
          divisible(7, 3)
          divisible(36, 6)
          divisible(9, 2)
OUTPUT:
          [1] "7 is not divisible by 3"
          [1] "36 is divisible by 6"
          [1] "9 is not divisible by 2"
  PROGRAM10                                          DATE:
   WRITE A FUNCTION USING IF AND ELSE, SWITCH, LOGICAL AND OR
                              OPERATION.
________________________________________________________________________
AIM:
  ALGORITHM:
   CODING:
IF CONDITION
              x <- 100
              if(x > 10){
              print(paste(x, "is greater than 10"))
              }
OUTPUT:
[1] "100 is greater than 10"
IF-ELSE CONDITION
              x <- 5
              # Check value is less than or greater than 10
              if(x > 10){
              print(paste(x, "is greater than 10"))
              }else{
              print(paste(x, "is less than 10"))
              }
OUTPUT:
              [1] "5 is less than 10"
SWITCH, LOGICAL AND OR OPERATION
              val1 = 6
              val2 = 7
              val3 = "s"
              result = switch(
                      val3,
                      "a"= cat("Addition =", val1 + val2),
                      "d"= cat("Subtraction =", val1 - val2),
                      "r"= cat("Division = ", val1 / val2),
                      "s"= cat("Multiplication =", val1 * val2),
                      "m"= cat("Modulus =", val1 %% val2),
                      "p"= cat("Power =", val1 ^ val2)
              )
              print(result)
OUTPUT:
              Multiplication = 42NULL
PROGRAM11                                                   DATE:
     WRITE A FUNCTION THAT USING FOR LOOP, WHILE LOOPS,
                    CONTROLLING LOOP.
_______________________________________________________________________________
AIM:
ALGORITHM:
 CODING:
FOR LOOP
          x <- letters[4:10]
          for(i in x){
          print(i)
          }
OUTPUT:
          [1] "d"
          [1] "e"
          [1] "f"
          [1] "g"
          [1] "h"
          [1] "i"
          [1] "j"
NESTED LOOPS
          # Defining matrix
          m <- matrix(2:15, 2)
          for (r in seq(nrow(m)))
          {
          for (c in seq(ncol(m))) {
                  print(m[r, c])
          }
          }
OUTPUT:
          [1] 2
          [1] 4
          [1] 6
          [1] 8
          [1] 10
          [1] 12
          [1] 14
          [1] 3
          [1] 5
          [1] 7
          [1] 9
          [1] 11
          [1] 13
WHILE LOOP
      x=1
      # Print 1 to 5
      while(x <= 5){
      print(x)
      x=x+1
      }
OUTPUT:
      [1] 1
      [1] 2
      [1] 3
      [1] 4
      [1] 5
REPEAT LOOP AND BREAK STATEMENT
      x=1
      # Print 1 to 5
      repeat{
      print(x)
      x=x+1
      if(x > 5){
      break
      }
      }
OUTPUT:
      [1] 1
      [1] 2
      [1] 3
      [1] 4
      [1] 5
PROGRAM12                                          DATE:
 WRITE A FUNCTION USING APPLY, LAPPLY, SAPPLY, MAPPLY AND
                           AGGREGATE.
____________________________________________________________________
AIM:
ALGORITHM:
   CODING:
   Apply() function
             m1 <- matrix(C<-(1:10),nrow=5, ncol=6)
             m1
             a_m1 <- apply(m1, 2, sum)
             a_m1
   OUTPUT:
lapply() function
             lapply(X, FUN)
             Arguments:
             -X: A vector or an object
             -FUN: Function applied to each element of x
             movies<- c("SPYDERMAN","BATMAN","VERTIGO","CHINATOWN")
             movies_lower<-lapply(movies, tolower)
             str(movies_lower)
OUTPUT:
             ## List of 4
             ## $:chr"spyderman"
             ## $:chr"batman"
             ## $:chr"vertigo"
             ## $:chr"chinatown"
We can use unlist() to convert the list into a vector.
             movies_lower<-unlist(lapply(movies,tolower))
             str(movies_lower)
OUTPUT:
             ## chr [1:4] "spyderman" "batman" "vertigo" "chinatown"
Sapply() function
              sapply(X, FUN)
              Arguments:
              -X: A vector or an object
              -FUN: Function applied to each element of x
We can measure the minimum speed and stopping distances of cars from the cars dataset.
              dt<- cars
              lmn_cars<- lapply(dt, min)
              smn_cars<- sapply(dt, min)
              lmn_cars
OUTPUT:
              ## $speed
              ## [1] 4
              ## $dist
              ## [1] 2
              smn_cars
OUTPUT:
              ## speed dist
              ## 4 2
              lmxcars<- lapply(dt, max)
              smxcars<- sapply(dt, max)
              lmxcars
OUTPUT:
              ## $speed
              ## [1] 25
              ## $dist
              ## [1] 120
              smxcars
OUTPUT:
             ## speed dist
             ## 25 120
We can use a user built-in function into lapply() or sapply(). We create a function named avg to
compute the average of the minimum and maximum of the vector.
              avg<- function(x) {
              ( min(x) + max(x) ) / 2}
              fcars<- sapply(dt, avg)
              fcars
OUTPUT
              ## speed dist
              ## 14.5 61.0