Introduction To R Programming
Introduction To R Programming
What is R Programming:
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 is freely available under the GNU General Public License, and pre-
compiled binary versions are provided for various operating systems like Linux,
Windows and Mac.
This programming language was named R, based on the first letter of
first name of the two R authors (Robert Gentleman and Ross Ihaka), and
partly a play on the name of the Bell Labs Language S.
Overview of R programming:
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.
The core of R is an interpreted computer language which allows
branching and looping as well as modular programming using functions. R
allows integration with the procedures written in the C, C++, .Net, Python or
FORTRAN languages for efficiency.
R is freely available under the GNU General Public License, and pre-
compiled binary versions are provided for various operating systems like Linux,
Windows and Mac.
1
R is free software distributed under a GNU-style copy left, and an official
part of the GNU project called GNU S.
Evolution of R:
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.
A large group of individuals has contributed to R by sending code and
bug reports.
Since mid-1997 there has been a core group (the "R Core Team") who
can modify the R source code archive.
Features of R:
As stated earlier, R is a programming language and software
environment for statistical analysis, graphics representation and reporting. The
following are the important features of R −
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,
R provides a suite of operators for calculations on arrays, lists, vectors
and matrices.
R provides a large, coherent and integrated collection of tools for data
analysis.
R provides graphical facilities for data analysis and display either directly
at the computer or printing at the papers.
As a conclusion, R is world’s most widely used statistics programming
language. It's the # 1 choice of data scientists and supported by a vibrant and
talented community of contributors. R is taught in universities and deployed in
mission critical business applications. This tutorial will teach you R
programming along with suitable examples in simple and easy steps.
2
Setup of R – Environment:
If you are willing to set up your environment for R, you can follow the
steps given below.
Windows Installation:
You can download the Windows installer version of R from R-3.2.2 for
Windows (32/64 bit) and save it in a local directory.
As it is a Windows installer (.exe) with a name "R-version-win.exe". You
can just double click and run the installer accepting the default settings. If
your Windows is 32-bit version, it installs the 32-bit version. But if your
windows is 64-bit, then it installs both the 32-bit and 64-bit versions.
After installation you can locate the icon to run the Program in a directory
structure "R\R3.2.2\bin\i386\Rgui.exe" under the Windows Program Files.
Clicking this icon brings up the R-GUI which is the R console to do R
Programming.
Basic Syntax of R:
As a convention, we will start learning R programming by writing a
"Hello, World!" program. Depending on the needs, you can program either at R
command prompt or you can use an R script file to write your program. Let's
check both one by one.
Command Prompt of R:
Once you have R environment setup, then it’s easy to start your R
command prompt by just typing the following command at your command
prompt −
>
This will launch R interpreter and you will get a prompt > where you can
start typing your program as follows −
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 −
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
OR 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.
v <- TRUE
print(class(v))
Logical TRUE, FALSE
it produces the following result −
[1] "logical"
v <- 23.5
print(class(v))
Numeric 12.3, 5, 999
it produces the following result −
[1] "numeric"
v <- 2L
print(class(v))
Integer 2L, 34L, 0L
it produces the following result −
[1] "integer"
v <- "TRUE"
'a' , '"good", print(class(v))
Character
"TRUE", '23.4' it produces the following result −
[1] "character"
v <- charToRaw("Hello")
"Hello" is stored print(class(v))
Raw
as 48 65 6c 6c 6f it produces the following result −
[1] "raw"
In R programming, the very basic data types are the R-objects
called vectors which hold elements of different classes as shown above.
Please note in R the number of classes is not confined to only the above six
types. For example, we can use many atomic vectors and create an array
whose class will become array.
Vectors
When you want to create vector with more than one element, you should
use c() function which means to combine the elements into a vector.
# Create a vector.
apple <- c('red','green',"yellow")
print(apple)
# Get the class of the vector.
print(class(apple))
When we execute the above code, it produces the following result −
Lists
A list is an R-object which can contain many different types of elements
inside it like vectors, functions and even another list inside it.
# Create a list.
list1 <- list(c(2,5,3),21.3,sin)
# Print the list.
print(list1)
6
When we execute the above code, it produces the following result −
[[1]]
[1] 2 5 3
[[2]]
[1] 21.3
[[3]]
function (x) .Primitive("sin")
Matrices
A matrix is a two-dimensional rectangular data set. It can be created
using a vector input to the matrix function.
# Create a matrix.
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 −
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 3x3 matrices each.
# Create an array.
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"
7
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.
# Create a vector.
apple_colors <- c('green','green','yellow','red','red','red','green')
# Create a factor object.
factor_apple <- factor(apple_colors)
# Print the factor.
print(factor_apple)
print(nlevels(factor_apple))
When we execute the above code, it produces the following result −
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.
8
gender height weight Age
1 Male 152.0 81 42
2 Male 171.5 93 38
3 Female 165.0 78 26
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
Single Element Vector
Even when you write just one value in R, it becomes a vector of length 1 and
belongs to one of the above vector types.
[1] 5.0 5.4 5.8 6.2 6.6 7.0 7.4 7.8 8.2 8.6 9.0
10
t <- c("Sun","Mon","Tue","Wed","Thurs","Fri","Sat")
u <- t[c(2,3,6)]
print(u)
[1] "Mon" "Tue" "Fri"
# Accessing vector elements using logical indexing.
v <- t[c(TRUE,FALSE,FALSE,FALSE,FALSE,TRUE,FALSE)]
print(v)
[1] "Sun" "Fri"
# Accessing vector elements using negative indexing.
x <- t[c(-2,-5)]
print(x)
[1] "Sun" "Tue" "Wed" "Fri" "Sat"
# Accessing vector elements using 0/1 indexing.
y <- t[c(0,0,0,0,0,0,1)]
print(y)
[1] "Sun"
Vector Manipulation
Vector arithmetic
Two vectors of same length can be added, subtracted, multiplied or divided
giving the result as a vector output.
11
[1] 12 88 0 40 0 22
# Vector division.
divi.result <- v1/v2
print(divi.result)
[1] 0.7500000 0.7272727 Inf 0.6250000 0.0000000 5.5000000
v1 <- c(3,8,4,5,0,11)
v2 <- c(4,11)
# V2 becomes c(4,11,4,11,4,11)
add.result <- v1+v2
print(add.result)
[1] 7 19 8 16 4 22
sub.result <- v1-v2
print(sub.result)
[1] -1 -3 0 -6 -4 0
Vector Element Sorting
Elements in a vector can be sorted using the sort() function.
R - Lists
Lists are the R objects which contain elements of different types like −
numbers, strings, vectors and another list inside it. A list can also contain a
matrix or a function as its elements. List is created using list() function.
Creating a List
Following is an example to create a list containing strings, numbers, vectors
and a logical values
[[1]]
[1] "Red"
[[2]]
[1] "Green"
[[3]]
[1] 21 32 11
[[4]]
[1] TRUE
[[5]]
[1] 51.23
[[6]]
[1] 119.1
13
# Create a list containing a vector, a matrix and a list.
list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow =
2),
list("green",12.3))
# Give names to the elements in the list.
names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list")
# Access the first element of the list.
print(list_data[1])
# Access the thrid element. As it is also a list, all its elements will
be printed.
print(list_data[3])
# Access the list element using the name of the element.
print(list_data$A_Matrix)
$`1st_Quarter`
[1] "Jan" "Feb" "Mar"
$A_Inner_list
$A_Inner_list[[1]]
[1] "green"
$A_Inner_list[[2]]
[1] 12.3
[,1] [,2] [,3]
[1,] 3 5 -2
[2,] 9 1 8
[[1]]
[1] "New element"
$
NULL
$`A Inner list`
[1] "updated element"
Merging Lists
You can merge many lists into one list by placing all the lists inside one list()
function.
[[1]]
[1] 1
15
[[2]]
[1] 2
[[3]]
[1] 3
[[4]]
[1] "Sun"
[[5]]
[1] "Mon"
[[6]]
[1] "Tue"
# Create lists.
list1 <- list(1:5)
print(list1)
list2 <-list(10:14)
print(list2)
# Convert the lists to vectors.
v1 <- unlist(list1)
v2 <- unlist(list2)
print(v1)
print(v2)
# Now add the vectors
result <- v1+v2
print(result)
[[1]]
[1] 1 2 3 4 5
[[1]]
16
[1] 10 11 12 13 14
[1] 1 2 3 4 5
[1] 10 11 12 13 14
[1] 11 13 15 17 19
R - Matrices
Matrices are the R objects in which the elements are arranged in a two-
dimensional rectangular layout. They contain elements of the same atomic
types. Though we can create a matrix containing only characters or only logical
values, they are not of much use. We use matrices containing numeric
elements to be used in mathematical calculations.
A Matrix is created using the matrix() function.
Syntax
The basic syntax for creating a matrix in R is −
17
# Elements are arranged sequentially by column.
N <- matrix(c(3:14), nrow = 4, byrow = FALSE)
print(N)
[,1] [,2] [,3]
[1,] 3 7 11
[2,] 4 8 12
[3,] 5 9 13
[4,] 6 10 14
# Define the column and row names.
rownames = c("row1", "row2", "row3", "row4")
colnames = c("col1", "col2", "col3")
P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames,
colnames))
print(P)
col1 col2 col3
row1 3 4 5
row2 6 7 8
row3 9 10 11
row4 12 13 14
18
# Access the element at 2nd column and 4th row.
print(P[4,2])
[1] 13
# Access only the 2nd row.
print(P[2,])
Matrix Computations
Various mathematical operations are performed on the matrices using the R
operators. The result of the operation is also a matrix.
The dimensions (number of rows and columns) should be same for the
matrices involved in the operation.
Matrix Addition & Subtraction
20
[1,] 0.6 -Inf 0.6666667
[2,] 4.5 0.4444444 1.5000000
R - Arrays
Arrays are the R data objects which can store data in more than two
dimensions. For example − If we create an array of dimension (2, 3, 4) then it
creates 4 rectangular matrices each with 2 rows and 3 columns. Arrays can
store only data type.
An array is created using the array() function. It takes vectors as input and
uses the values in the dim parameter to create an array.
Example
The following example creates an array of two 3x3 matrices each with 3 rows
and 3 columns.
, , 1
[,1] [,2] [,3]
[1,] 5 10 13
[2,] 9 11 14
[3,] 3 12 15
, , 2
[,1] [,2] [,3]
[1,] 5 10 13
[2,] 9 11 14
[3,] 3 12 15
21
Naming Columns and Rows
We can give names to the rows, columns and matrices in the array by using
the dimnames parameter.
, , Matrix1
ROW1 ROW2 ROW3
COL1 5 10 13
COL2 9 11 14
COL3 3 12 15
, , Matrix2
ROW1 ROW2 ROW3
COL1 5 10 13
COL2 9 11 14
COL3 3 12 15
Accessing Array Elements
23
Calculations Across Array Elements
We can do calculations across the elements in an array using
the apply()function.
Syntax
, , 1
[,1] [,2] [,3]
[1,] 5 10 13
[2,] 9 11 14
[3,] 3 12 15
, , 2
[,1] [,2] [,3]
[1,] 5 10 13
24
[2,] 9 11 14
[3,] 3 12 15
[1] 56 68 60
R - Factors
Factors are the data objects which are used to categorize the data and store it
as levels. They can store both strings and integers. They are useful in the
columns which have a limited number of unique values. Like "Male, "Female"
and True, False etc. They are useful in data analysis for statistical modeling.
Factors are created using the factor () function by taking a vector as input.
Example
25
2 151 49 male
3 162 66 female
4 139 53 female
5 166 67 male
6 147 52 female
7 122 40 male
# Test if the gender column is a factor.
print(is.factor(input_data$gender))
[1] TRUE
# Print the gender column so see the levels.
print(input_data$gender)
[1] male male female female male female male
Levels: female male
Changing the Order of Levels
The order of the levels in a factor can be changed by applying the factor
function again with new order of the levels.
data <-
c("East","West","East","North","North","East","West","West","West","East"
,"North")
# Create the factors
factor_data <- factor(data)
print(factor_data)
[1] East West East North North East West West West East North
Levels: East North West
# Apply the factor function with required order of the level.
new_order_data <- factor(factor_data,levels = c("East","West","North"))
print(new_order_data)
[1] East West East North North East West West West East North
Levels: East West North
Generating Factor Levels
We can generate factor levels by using the gl() function. It takes two integers
as input which indicates how many levels and how many times each level.
Syntax
gl(n, k, labels)
Following is the description of the parameters used −
n is a integer giving the number of levels.
k is a integer giving the number of replications.
labels is a vector of labels for the resulting factor levels.
Example
26
print(v)
Tampa Tampa Tampa Tampa Seattle Seattle Seattle Seattle Boston
[10] Boston Boston Boston
Levels: Tampa Seattle Boston
R - Data Frames
A data frame is a table or a two-dimensional array-like structure in which each
column contains values of one variable and each row contains one set of
values from each column.
Following are the characteristics of a data frame.
The column names should be non-empty.
The row names should be unique.
The data stored in a data frame can be of numeric, factor or character
type.
Each column should contain same number of data items.
Create Data Frame
27
4 4 Ryan 729.00 2014-05-11
5 5 Gary 843.25 2015-03-27
emp.data.emp_name emp.data.salary
1 Rick 623.30
2 Dan 515.20
3 Michelle 611.00
4 Ryan 729.00
5 Gary 843.25
29
Extract the first two rows and then all columns
Extract 3rd and 5th row with 2nd and 4th column
30
emp_name start_date
3 Michelle 2014-11-15
5 Gary 2015-03-27
Add Row
To add more rows permanently to an existing data frame, we need to bring in
the new rows in the same structure as the existing data frame and use the
rbind() function.
31
In the example below we create a data frame with new rows and merge it with
the existing data frame to create the final data frame.
32
7 7 Pranab 722.50 2013-07-30 Operations
8 8 Tusar 632.80 2014-06-17 Fianance
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.
1. A valid variable name consists of letters, numbers and the dot or
underline characters.
2. The variable name starts with a letter or the dot not followed by a
number.
var_name% Invalid Has the character '%'. Only dot(.) and underscore
allowed.
2var_name invalid Starts with a number
.var_name , valid Can start with a dot(.) but the dot(.)should not be
followed by a number.
var.name
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.
[1] 0 1 2 3
var.1 is 0 1 2 3
var.2 is learn R
var.3 is 1 1
Note − The vector c(TRUE,1) has a mix of logical and numeric class. So logical
class is coerced to numeric class making TRUE as 1.
Finding Variables
To know all the variables currently available in the workspace we use
the ls()function. Also the ls() function can use patterns to match the variable
names.
print(ls())
34
When we execute the above code, it produces the following result −
The variables starting with dot(.) are hidden, they can be listed using
"all.names = TRUE" argument to ls() function.
print(ls(all.name = TRUE))
When we execute the above code, it produces the following result −
Deleting Variables
Variables can be deleted by using the rm() function. Below we delete the
variable var.3. On printing the value of the variable error is thrown.
rm(var.3)
print(var.3)
When we execute the above code, it produces the following result −
[1] "var.3"
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 −
35
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 −
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Miscellaneous Operators
Arithmetic Operators
Following table shows the arithmetic operators supported by R language.
The operators act on each element of the vector.
v <- c( 2,5.5,6)
t <- c(8, 3, 4)
+ Adds two vectors print(v+t)
it produces the following result −
[1] 10.0 8.5 10.0
v <- c( 2,5.5,6)
Subtracts second t <- c(8, 3, 4)
− print(v-t)
vector from the first
it produces the following result −
[1] -6.0 2.5 2.0
v <- c( 2,5.5,6)
Multiplies both
* t <- c(8, 3, 4)
vectors print(v*t)
it produces the following result −
36
[1] 16.0 16.5 24.0
v <- c( 2,5.5,6)
Divide the first t <- c(8, 3, 4)
print(v/t)
/ vector with the
When we execute the above code, it produces
second the following result −
[1] 0.250000 1.833333 1.500000
v <- c( 2,5.5,6)
Give the remainder
t <- c(8, 3, 4)
%% of the first vector print(v%%t)
with the second it produces the following result −
[1] 2.0 2.5 2.0
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.
37
Checks if each element of v <- c(2,5.5,6,9)
the first vector is less than t <- c(8,2.5,14,9)
< print(v < t)
the corresponding element it produces the following result −
of the second vector. [1] TRUE FALSE TRUE FALSE
Logical Operators
Following table shows the logical operators supported by R language. It is
applicable only to vectors of type logical, numeric or complex. All numbers
greater than 1 are considered as logical value TRUE.
Each element of the first vector is compared with the corresponding element of
the second vector. The result of comparison is a Boolean value.
38
It is called Element-wisev <- c(3,1,TRUE,2+3i)
Logical AND operator. It t <- c(3,1,FALSE,2+3i)
print(v&t)
combines each element it produces the following result −
of the first vector with [1] TRUE TRUE FALSE TRUE
& the corresponding
element of the second
vector and gives an
output TRUE if both the
elements are TRUE.
The logical operator && and || considers only the first element of the vectors
and give a vector of single element as output.
39
only if both are TRUE. [1] TRUE
Assignment Operators
These operators are used to assign values to vectors.
v1 <- c(3,1,TRUE,2+3i)
v2 <<- c(3,1,TRUE,2+3i)
<−
v3 = c(3,1,TRUE,2+3i)
or print(v1)
Called Left print(v2)
=
Assignment print(v3)
or 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
c(3,1,TRUE,2+3i) -> v1
c(3,1,TRUE,2+3i) ->> v2
->
Called Right print(v1)
or print(v2)
Assignment
->> 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.
40
for a vector.
v1 <- 8
v2 <- 12
This operator is used to t <- 1:10
print(v1 %in% t)
%in% identify if an element
print(v2 %in% t)
belongs to a vector. it produces the following result −
[1] TRUE
[1] FALSE
41
R - Functions
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.
In R, a function is an object so the R interpreter is able to pass control to
the function, along with arguments that may be necessary for the function to
accomplish the actions.
The function in turn performs its task and returns control to the
interpreter as well as any result which may be stored in other objects.
Function Definition
An R function is created by using the keyword function. The basic
syntax of an R function definition is as follows −
42
Built-in Function
Simple examples of in-built functions
are seq(), mean(), max(), sum(x) and paste(...) etc. They are directly
called by user written programs. You can refer most widely used R functions.
[1] 32 33 34 35 36 37 38 39 40 41 42 43 44
[1] 53.5
[1] 1526
User-defined Function
We can create user-defined functions in R. They are specific to what a user
wants and once created they can be used like the built-in functions. Below is
an example of how a function is created and used.
[1] 1
43
[1] 4
[1] 9
[1] 16
[1] 25
[1] 36
Calling a Function without an Argument
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
Calling a Function with Argument Values (by position and by name)
The arguments to a function call can be supplied in the same sequence as
defined in the function or they can be supplied in a different sequence but
assigned to the names of the arguments.
[1] 26
[1] 58
44
Calling a Function with Default Argument
We can define the value of the arguments in the function definition and call the
function without supplying any argument to get the default result. But we can
also call such functions by supplying new values of the argument and get non
default result.
[1] 18
[1] 45
[1] 36
[1] 6
Error in print(b) : argument "b" is missing, with no default
45
R - Decision making
Decision making structures require the programmer to specify one or
more conditions to be evaluated or tested by the program, along with a
statement or statements to be executed if the condition is determined to
be true, and optionally, other statements to be executed if the condition is
determined to be false.
Following is the general form of a typical decision making structure found
in most of the programming languages −
1 if statement
An if statement consists of a Boolean expression followed by one or
more statements.
2 if...else statement
An if statement can be followed by an optional else statement, which
executes when the Boolean expression is false.
3 switch statement
A switch statement allows a variable to be tested for equality
against a list of values.
46
R - Loops
There may be a situation when you need to execute a block of code
several number of times. In general, statements are executed sequentially.
The first statement in a function is executed first, followed by the second, and
so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of
statements multiple times and the following is the general form of a loop
statement in most of the programming languages −
1 repeat loop
Executes a sequence of statements multiple times and abbreviates
the code that manages the loop variable.
2 while loop
47
Repeats a statement or group of statements while a given condition is
true. It tests the condition before executing the loop body.
3 for loop
Like a while statement, except that it tests the condition at the end of
the loop body.
1 break statement
Terminates the loop statement and transfers execution to the
statement immediately following the loop.
2 Next statement
The next statement simulates the behavior of R switch.
48
R - Strings
Any value written within a pair of single quote or double quotes in R is treated
as a string. Internally R stores every string within double quotes, even when
you create them with single quote.
Rules Applied in String Construction
The quotes at the beginning and end of a string should be both double
quotes or both single quote. They cannot be mixed.
Double quotes can be inserted into a string starting and ending with
single quote.
Single quote can be inserted into a string starting and ending with double
quotes.
Double quotes cannot be inserted into a string starting and ending with
double quotes.
Single quote cannot be inserted into a string starting and ending with
single quote.
Examples of Valid Strings
Following examples clarify the rules about creating a string in R.
49
Examples of Invalid Strings
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 −
a <- "Hello"
b <- 'How'
c <- "are you? "
print(paste(a,b,c))
[1] "Hello How are you? "
50
print(paste(a,b,c, sep = "-"))
[1] "Hello-How-are you? "
print(paste(a,b,c, sep = "", collapse = ""))
[1] "HelloHoware you? "
51
print(result)
[1] "23.47000"
# Format treats everything as a string.
result <- format(6)
print(result)
[1] "6"
# Numbers are padded with blank in the beginning for width.
result <- format(13.7, width = 6)
print(result)
[1] " 13.7"
# Left justify strings.
result <- format("Hello", width = 8, justify = "l")
print(result)
[1] "Hello "
# Justfy string with center.
result <- format("Hello", width = 8, justify = "c")
print(result)
[1] " Hello "
nchar(x)
[1] 30
52
Changing the case – toupper() & tolower() functions
These functions change the case of characters of a string.
Syntax
The basic syntax for toupper() & tolower() function is −
toupper(x)
tolower(x)
substring(x,first,last)
[1] "act"
53
R - Packages
R packages are a collection of R functions, complied code and sample data.
They are stored under a directory called "library" in the R environment. By
default, R installs a set of packages during installation. More packages are
added later, when they are needed for some specific purpose. When we start
the R console, only the default packages are available by default. Other
packages which are already installed have to be loaded explicitly to be used by
the R program that is going to use them.
All the packages available in R language are listed at R Packages.
Below is a list of commands to be used to check, verify and use the R
packages.
Check Available R Packages
Get library locations containing R packages
.libPaths()
When we execute the above code, it produces the following result. It may vary
depending on the local settings of your pc.
library()
When we execute the above code, it produces the following result. It may vary
depending on the local settings of your pc.
54
search()
When we execute the above code, it produces the following result. It may vary
depending on the local settings of your pc.
install.packages("Package Name")
# Install the package named "XML".
install.packages("XML")
R - Data Reshaping
Data Reshaping in R is about changing the way data is organized into rows and
columns. Most of the time data processing in R is done by taking the input
data as a data frame. It is easy to extract data from the rows and columns of a
data frame but there are situations when we need the data frame in a format
that is different from format in which we received it. R has many functions to
split, merge and change the rows to columns and vice-versa in a data frame.
57
Merging Data Frames
We can merge two data frames by using the merge() function. The data
frames must have same column names on which the merging happens.
In the example below, we consider the data sets about Diabetes in Pima Indian
Women available in the library names "MASS". we merge the two data sets
based on the values of blood pressure("bp") and body mass index("bmi"). On
choosing these two columns for merging, the records where values of these
two variables match in both data sets are combined together to form a single
data frame.
library(MASS)
merged.Pima <- merge(x = Pima.te, y = Pima.tr,
by.x = c("bp", "bmi"),
by.y = c("bp", "bmi")
)
print(merged.Pima)
nrow(merged.Pima)
bp bmi npreg.x glu.x skin.x ped.x age.x type.x npreg.y glu.y skin.y
ped.y
1 60 33.8 1 117 23 0.466 27 No 2 125 20
0.088
2 64 29.7 2 75 24 0.370 33 No 2 100 23
0.368
3 64 31.2 5 189 33 0.583 29 Yes 3 158 13
0.295
4 64 33.2 4 117 27 0.230 24 No 1 96 27
0.289
5 66 38.1 3 115 39 0.150 28 No 1 114 36
0.289
6 68 38.5 2 100 25 0.324 26 No 7 129 49
0.439
58
7 70 27.4 1 116 28 0.204 21 No 0 124 20
0.254
8 70 33.1 4 91 32 0.446 22 No 9 123 44
0.374
9 70 35.4 9 124 33 0.282 34 No 6 134 23
0.542
10 72 25.6 1 157 21 0.123 24 No 4 99 17
0.294
11 72 37.7 5 95 33 0.370 27 No 6 103 32
0.324
12 74 25.9 9 134 33 0.460 81 No 8 126 38
0.162
13 74 25.9 1 95 21 0.673 36 No 8 126 38
0.162
14 78 27.6 5 88 30 0.258 37 No 6 125 31
0.565
15 78 27.6 10 122 31 0.512 45 No 6 125 31
0.565
16 78 39.4 2 112 50 0.175 24 No 4 112 40
0.236
17 88 34.5 1 117 24 0.403 40 Yes 4 127 11
0.598
age.y type.y
1 31 No
2 21 No
3 24 No
4 21 No
5 21 No
6 43 Yes
7 36 Yes
8 40 No
9 29 Yes
10 28 No
59
11 55 No
12 39 No
13 39 No
14 49 Yes
15 49 Yes
16 38 No
17 28 No
[1] 17
60