







































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!








































































AIM: Implement all basic R commands
R INTRODUCTION R is a programming language and software environment for statistical analysis, graphics representation and reporting. R was created by Ross Ihaka and Robert Gentleman at the University of Auckland, New Zealand, and is currently developed by the R Development Core Team. R was initially written by Ross Ihaka and Robert Gentleman at the Department of Statistics of the University of Auckland in Auckland, New Zealand. R made its first appearance in 1993. R is a well-developed, simple and effective programming language which includes conditionals, loops, user defined recursive functions and input and output facilities. R has an effective data handling and storage facility. On February 2000, the first version of R for binary files is released. Later on February 2003, version of R 1.6.2 was released. The latest version of R is R 4.1.1 which was released in August,2021.
R COMMANDS First it will be easy to start your R command prompt by just typing the following command at your command prompt: $ R This will launch R interpreter and you will get a prompt > where you can start typing your program as follows: > myString <- "Hello, World!" > print ( myString) [1] "Hello, World!" R Script File Usually, you will do your programming by writing your programs in script files and then you execute those scripts at your command prompt with the help of R interpreter called Rscript. So let's start with writing following code in a text file called test.R as under:
myString <- "Hello, World!" print ( myString) Save the above code in a file test.R and execute it at Linux command prompt as given below.Even if you are using Windows or other system, syntax will remain same. $ Rscript test.R When we run the above program, it produces the following result. [1] "Hello, World!" Comments Comments are like helping text in your R program and they are ignored by the interpreter while executing your actual program. Single comment is written using # in the beginning of the statement as follows:
># My first program in R Programming R does not support multi-line comments but you can perform a trick which is something as follows: >if(FALSE){ "This is a demo for multi-line comments and it should be put inside either a single of double quote" } >myString <- "Hello, World!" >print ( myString) Though above comments will be executed by R interpreter, they will not interfere with your actual program. You should put such comments inside, either single or double quote.
R-Data Types Variables are nothing but reserved memory locations to store values. This means that, when you create a variable you reserve some space in memory. The variables are assigned with R-Objects and the data type of the R-object becomes the data type of the variable. There are many types of R-objects. The frequently used ones are: Vectors Lists Matrices Arrays Factors Data Frames The simplest of these objects is the vector object and there are six data types of these atomic vectors, also termed as six classes of vectors. The other R-Objects are built upon the atomic vectors. Data Type Example Verify Logical TRUE , FALSE > v <- TRUE >print(class(v)) result: [1] "logical"
Numeric 12.3, 5, 999 > v <- 23. >print(class(v)) Result: [1] "numeric" Integer 2L, 34L, 0L >v <- 2L >print(class(v)) result: [1] "integer"
Complex 3 + 2i >v <- 2+5i
>M = matrix( c('a','a','b','c','b','a'), nrow=2,ncol=3,byrow = TRUE) >print(M) When we execute the above code, it produces the following result: [,1] [,2] [,3] [1,] "a" "a" "b" [2,] "c" "b" "a"
Arrays While matrices are confined to two dimensions, arrays can be of any number of dimensions. The array function takes a dim attribute which creates the required number of dimension. In the below example we create an array with two elements which are 3x matrices each.
>a <- array(c('green','yellow'),dim=c(3,3,2)) >print(a) When we execute the above code, it produces the following result: , , 1
[,1] [,2] [,3] [1,] "green" "yellow" "green" [2,] "yellow" "green" "yellow" [3,] "green" "yellow" "green"
, , 2
[,1] [,2] [,3] [1,] "yellow" "green" "yellow" [2,] "green" "yellow" "green" [3,] "yellow" "green" "yellow"
Factors Factors are the r-objects which are created using a vector. It stores the vector along with the distinct values of the elements in the vector as labels. The labels are always character irrespective of whether it is numeric or character or Boolean etc. in the input vector. They are useful in statistical modeling. Factors are created using the factor() function. The nlevels functions gives the count of levels.
>apple_colors <- c('green','green','yellow','red','red','red','green')
>factor_apple <- factor(apple_colors)
>print(factor_apple) >print(nlevels(factor_apple)) When we execute the above code, it produces the following result:
[1] green green yellow red red red yellow green Levels: green red yellow
[1] 3 Data Frames Data frames are tabular data objects. Unlike a matrix in data frame each column can contain different modes of data. The first column can be numeric while the second column can be character and third column can be logical. It is a list of vectors of equal length. Data Frames are created using the data.frame() function.
>BMI <- data.frame( gender = c("Male", "Male","Female"), height = c(152, 171.5, 165), weight = c(81,93, 78), Age =c(42,38,26) ) >print(BMI) When we execute the above code, it produces the following result: gender height weight Age 1 Male 152.0 81 42 2 Male 171.5 93 38 3 Female 165.0 78 26
R-Variables A variable provides us with named storage that our programs can manipulate. A variable in R can store an atomic vector, group of atomic vectors or a combination of many R-objects. A valid variable name consists of letters, numbers and the dot or underline characters. The variable name starts with a letter or the dot not followed by a number. Eg:->var_name2. valid. Because, it has letters, numbers, dot and underscore >var_name% Invalid. Has the character '%'. Only dot(.) and underscore allowed. Variable Assignment The variables can be assigned values using leftward, rightward and equal to operator. The values of the variables can be printed using print() or cat()function. The cat() function combines multiple items into a continuous print output.
>var.1 = c(0,1,2,3)
>var.2 <- c("learn","R")
>c(TRUE,1) -> var. >print(var.1) >cat ("var.1 is ", var.1 ,"\n")
Error in print(var.3) : object 'var.3' not found All the variables can be deleted by using the rm() and ls() function together. >rm(list=ls()) >print(ls()) When we execute the above code, it produces the following result: character(0)
R-Operators An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. R language is rich in built-in operators and provides following types of operators. Types of Operators: We have the following types of operators in R programming: Arithmetic Operators Relational Operators Logical Operators Assignment Operators Miscellaneous Operators Arithmetic Operators Following table shows the arithmetic operators supported by R language. The operators act on each element of the vector. Operator Description Example
− Subtracts second >v <- c( 2,5.5,6) from the first >t <- c(8, 3, 4) >print(v-t) it produces the following result: [1] -6.0 2.5 2.
/ Divide the first >v <- c( 2,5.5,6) vector with the >t <- c(8, 3, 4)
second >print(v/t) When we execute the above code, it produces the following result: [1] 0.250000 1.833333 1.
%% Give the >v <- c( 2,5.5,6) reaminder of the >t<- c(8, 3, 4) first vector with >print(v%%t) the second It produces the following result: [1] 2.0 2.5 2.
%/% The result of >v <- c( 2,5.5,6) Division of first >t <- c(8, 3, 4) Vector with >print(v%/%t) Second (quotient) it produces the following result: [1] 0 1 1 ^ The first vector >v <- c( 2,5.5,6) Raised to the exponent >t <- c(8, 3, 4) of second vector >print(v^t) it produces the following result: [1] 256.000 166.375 1296. Relational Operators Following table shows the relational operators supported by R language. Each element of the first vector is compared with the corresponding element of the second vector. The result of comparison is a Boolean value. Operator Description Example > Checks if each element of the first vector is greater than the corresponding element of the second vector.
>v <- c(2,5.5,6,9) >t <- c(8,2.5,14,9) >print(v>t) it produces the following result: [1] FALSE TRUE FALSE FALSE < Checks if each element of the first vector is less than the corresponding element of the second vector.
>v <- c(2,5.5,6,9) >t <- c(8,2.5,14,9) >print(v < t) it produces the following result: [1] TRUE FALSE TRUE FALSE == Checks if each element of the first vector is equal to the corresponding element of the second vector.
>v <- c(2,5.5,6,9) >t <- c(8,2.5,14,9) >print(v==t) it produces the following result: [1] FALSE FALSE FALSE
The logical operator && and || considers only the first element of the vectors and give a vector of single element as output. Operator Description Example && Called Logical AND operator. Takes first element of both the vectors and gives the TRUE only if both are TRUE.
>v <- c(3,0,TRUE,2+2i) >t <- c(1,3,TRUE,2+3i) >print(v&&t) it produces the following result: [1] TRUE || Called Logical OR operator. Takes first element of both the vectors and gives the TRUE only if both are TRUE.
>v <- c(0,0,TRUE,2+2i) >t <- c(0,3,TRUE,2+3i) >print(v||t) it produces the following result: [1] FALSE Assignment Operators These operators are used to assign values to vectors. Operator Description Example <-
or
=
or
<<-
Called Left Assignment
>v1 <- c(3,1,TRUE,2+3i) >v2 <<- c(3,1,TRUE,2+3i) >v3 = c(3,1,TRUE,2+3i) >print(v1) >print(v2) >print(v3) it produces the following result: [1] 3+0i 1+0i 1+0i 2+3i [1] 3+0i 1+0i 1+0i 2+3i [1] 3+0i 1+0i 1+0i 2+3i ->
or ->>
Called Right Assignment
>c(3,1,TRUE,2+3i) -> v >c(3,1,TRUE,2+3i) ->> v >print(v1) >print(v2) it produces the following result: [1] 3+0i 1+0i 1+0i 2+3i [1] 3+0i 1+0i 1+0i 2+3i
Miscellaneous Operators These operators are used to for specific purpose and not general mathematical or logical computation. Operator Description Example
: Colon operator. It creates the series of numbers in sequence for a vector.
>v <- 2: >print(v) it produces the following result: [1] 2 3 4 5 6 7 8 %in% This operator is used to identify if an element belongs to a vector.
>v1 <- 8 >v2 <- 12 >t <- 1: >print(v1 %in% t) >print(v2 %in% t) it produces the following result: [1] TRUE [1] FALSE %*% This operator is used to multiply a matrix with its transpose.
>M = matrix( c(2,6,5,1,10,4), nrow=2,ncol=3,byrow = TRUE) >t = M %*% t(M) >print(t) it produces the following result: [,1] [,2] [1,] 65 82 [2,] 82 117
R – Decision making Decision making structures require the programmer to specify one or more conditions to be evaluated or tested by the program. R -If Statement An if statement consists of a Boolean expression followed by one or more statements. Example x <- 30L if(is.integer(x)){ print("X is an Integer") } When the above code is compiled and executed, it produces the following result: [1] "X is an Integer" R – If...Else Statement An if statement can be followed by an optional else statement which executes when the boolean expression is false. Example x <- c("what","is","truth") if("Truth" %in% x){ print("Truth is found") } else { print("Truth is not found")
When the above code is compiled and executed, it produces the following result: [1] "Hello" "loop" [1] "Hello" "loop" [1] "Hello" "loop" [1] "Hello" "loop" R -While Loop The While loop executes the same code again and again until a stop condition is met. Example v <- c("Hello","while loop") cnt <- 2 while (cnt < 7){ print(v) cnt = cnt + 1 } When the above code is compiled and executed, it produces the following result : [1] "Hello" "while loop" [1] "Hello" "while loop" [1] "Hello" "while loop" [1] "Hello" "while loop" [1] "Hello" "while loop" R – For Loop A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. Example v <- LETTERS[1:4] for ( i in v) { print(i) } When the above code is compiled and executed, it produces the following result: [1] "A" [1] "B" [1] "C" [1] "D"
Loop Control Statements Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. R – Break Statement The break statement in R programming language has the following two usages: When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop. It can be used to terminate a case in the switch statement.
Example v <- c("Hello","loop") cnt <- 2 repeat{ print(v) cnt <- cnt+ if(cnt > 5){ break } } When the above code is compiled and executed, it produces the following result: [1] "Hello" "loop" [1] "Hello" "loop" [1] "Hello" "loop" [1] "Hello" "loop" R – Next Statement The next statement in R programming language is useful when we want to skip the current iteration of a loop without terminating it. On encountering next, the R parser skips further evaluation and starts next iteration of the loop. Example v <- LETTERS[1:6] for ( i in v){ if (i == "D"){ next } print(i) } When the above code is compiled and executed, it produces the following result: [1] "A" [1] "B" [1] "C" [1] "E" [1] "F"
R – Function A function is a set of statements organized together to perform a specific task. R has a large number of in-built functions and the user can create their own functions. Function Definition An R function is created by using the keyword function. The basic syntax of an R function definition is as follows: function_name <- function(arg_1, arg_2, ...) { Function body } Where,
new.function() When we execute the above code, it produces the following result: [1] 1 [1] 4 [1] 9 [1] 16 [1] 25
R – Strings Any value written within a pair of single quote or double quotes in R is treated as a string. >a<-"R programming " >a Output: [1] "R programming "
String Manipulation Concatenating Strings -paste() function Many strings in R are combined using the paste() function. It can take any number of arguments to be combined together. Syntax The basic syntax for paste function is : paste(..., sep = " ", collapse = NULL) Example >a <- "Hello" >b <- 'How' c <- "are you? " >print(paste(a,b,c)) >print(paste(a,b,c, sep = "-")) >print(paste(a,b,c, sep = "", collapse = "")) When we execute the above code, it produces the following result: [1] "Hello How are you? " [1] "Hello-How-are you? " [1] "HelloHoware you? " Formatting numbers & strings -format() function Numbers and strings can be formatted to a specific style using format()function. Syntax The basic syntax for format function is : format(x, digits, nsmall,scientific,width,justify = c("left", "right", "centre", "none"))
>result <- format(23.47, nsmall = 5) >print(result) Output: [1] "23.47000"
Counting number of characters in a string -ncahr() function This function counts the number of characters including spaces in a string. Syntax nchar(x) where, x is the vector input. Example >result <- nchar("Count the number of characters") >print(result) When we execute the above code, it produces the following result: [1] 30 Changing the case - toupper() & tolower() functions toupper() and tolower()These functions change the case of characters of a string. Example
>result <- toupper("Changing To Upper") >print(result)
>result <- tolower("Changing To Lower") >print(result) When we execute the above code, it produces the following result: [1] "CHANGING TO UPPER" [1] "changing to lower" Extracting parts of a string - substring() function This function extracts parts of a String. Syntax The basic syntax for substring() function is : substring(x,first,last) Example
>result <- substring("Extract", 5, 7) >print(result) When we execute the above code, it produces the following result: [1] "act"
R – Vectors Vectors are the most basic R data objects and there are six types of atomic vectors. They are logical, integer, double, complex, character and raw. Vector Creation >x<-"abc" >x [1] "abc" Using sequence (Seq.) operator
>print(seq(5, 9, by=0.4))
AIM:-To interact data through .CSV files(Import form and export to .CSV files) In R, we can read data from files stored outside the R environment. We can also write data into files which will be stored and accessed by the operating system. R can read and write into various file formats like csv, excel, xml etc. In this chapter we will learn to read data from a csv file and then write data into a csv file. The file should be present in current working directory so that R can read it. Of course we can also set our own directory and read files from there. In R programming, to install a package. We use, install.packages(―package name‖) command. To load the installed package. We use, library(package name) command. Getting and Setting the Working Directory You can check which directory the R workspace is pointing to using the getwd() function. You can also set a new working directory using setwd()function.
>getwd() [1] "c:/users/aliet/Desktop"
>setwd("c:/users/aliet/Desktop") >getwd() [1] "c:/users/aliet/Desktop" Input as CSV File The csv file is a text file in which the values in the columns are separated by a comma. Let's consider the following data present in the file named input.csv. You can create this file using windows notepad by copying and pasting this data. Save the file as input.csv using the save As All files(.) option in notepad. id,name,salary,start_date,dept 1,Rick,623.3,2012-01-01,IT 2,Dan,515.2,2013-09-23,Operations 3,Michelle,611,2014-11-15,IT 4,Ryan,729,2014-05-11,HR 5,Gary,843.25,2015-03-27,Finance Reading a CSV File Following is a simple example of read.csv() function to read a CSV file available in your current working directory − >data <- read.csv("input.csv") >data When we execute the above code, it produces the following result − id, name, salary, start_date, dept 1 1 Rick 623.30 2012-01-01 IT 2 2 Dan 515.20 2013-09-23 Operations 3 3 Michelle 611.00 2014-11-15 IT 4 4 Ryan 729.00 2014-05-11 HR 5 NA Gary 843.25 2015-03-27 Finance
Analyzing the CSV File By default the read.csv() function gives the output as a data frame. This can be easily checked as follows. Also we can check the number of columns and rows. >data <- read.csv("input.csv") >print(is.data.frame(data)) >ncol(data) >nrow(data) When we execute the above code, it produces the following result − [1] TRUE [1] 5 [1] 5 Once we read data in a data frame, we can apply all the functions applicable to data frames as explained in subsequent section. Get the maximum salary
>data <- read.csv("input.csv")
>sal <- max(data$salary) >print(sal) When we execute the above code, it produces the following result − [1] 843. Get the details of the person with max salary We can fetch rows meeting specific filter criteria similar to a SQL where clause.
>data <- read.csv("input.csv")
>sal <- max(data$salary)
>retval <- subset(data, salary == max(salary)) >retval When we execute the above code, it produces the following result − Id name salary start_date dept 5 NA Gary 843.25 2015-03-27 Finance Get all the people working in IT department
>data <- read.csv("input.csv") >retval <- subset( data, dept == "IT") >retval When we execute the above code, it produces the following result − id name salary start_date dept 1 1 Rick 623.3 2012-01-01 IT 3 3 Michelle 611.0 2014-11-15 IT Get the persons in IT department whose salary is greater than 600