You are on page 1of 76

Statistics using R

Statistics using R 1
Module-05 : Introduction to R- Packages
 Scientific Calculator- Inspecting Variables-
Vectors Matrices and Arrays- Lists and Data
Frames- Functions- Strings.
 Factors- Flow Control and Loops- Advanced
Looping- Date and Times.
 Descriptive Statistics and Graphics
 Obtaining summary statistics;
 Generating tables Pie charts, Box plots,
Histogram; exercises.

Statistics using R 2
Introduction to R

Statistics using R 3
Import Data from
clients

Data Data Data


Selection Analysis Presentation

Export Output to
clients
Statistics using R 4
Introduction
• R is an integrated suite of software facilities
for data manipulation, calculation and
graphical display
• R language used for performing statistical
operations
• R is command line driven program
• R can be used in Windows, Linux, Mac OS
• R is case sensitive
Statistics using R 5
Comparison of R
R Python
Learning Difficult at the beginning Easy to learn
Average salary (in $) 99 100
Database size Handle huge data Handle huge data
Environment Rstudio Ipthon Notebook
Disadvantages Slow learning due to many Not as many libraries as R
libraries
Advantages R makes graphs more Speed is notable feature in
visually python

Statistics using R 6
R SPSS
Visualization Offer more opportunities Graphical capabilities of
to customize graphs due to SPSS are purely restricted
wide range of modules to inbuilt functions
Cost R is open source free IBM SPSS is not free. To
software learn SPSS, trial version
has to be used first
Platform R is command driven It is GUI (Graphically user
language Interface)
Decision making For decision trees, R has no SPSS is user friendly and
algorithms offers decision tree
algorithms

Statistics using R 7
R Excel
Ease of Use R is difficult to learn in Excel is bit easy to use
initial days as to remember because it is point and
the different functions click platform
Statistical Analysis R has many updated Excel has all basic analysis
statistical analysis features
functions
Careers Data science (using R) has Countless jobs are looking
more job opportunities for Excel also, but R has
with high salaries high earning potential
when compared to Excel

Statistics using R 8
Installation of R

Statistics using R 9
Statistics using R 10
Statistics using R 11
Statistics using R 12
Statistics using R 13
Statistics using R 14
Statistics using R 15
Statistics using R 16
Statistics using R 17
18

Explanation of Rstudio Page

Statistics using R
Data Structures in R
• Scalar
• Vector
• Matrix
• Data frame

Statistics using R 19
Input of Data
• Manual Data entry
– Values
– Vectors
– Matrices
• Importing Data file from computer to R (CSV,
Excel, Txt)

Statistics using R 20
Operators and operations in R
Assignment Operators
Arithmetic Operators
Relational Operators
Logical Operators
Other operators

Statistics using R 21
Assignment operators
Operator Description

<- Called Left Assignment operator, used to assign


<<- the values for variables

-> Called Right Assignment Operator, used to assign


->> the values for variables

= Used to assign the values for variables

Statistics using R 22
Arithmetic operators
Operator Description

Add two values, vectors, matrices


+
Subtract two values, vectors, matrices
-
Multiplies two values, vectors
*
Divide the first vector with the second
/
Give the remainder of the first vector with the second
%%
Give the quotient of the first vector with the second
%/%
The first vector raised to the exponent of second vector
^
Statistics using R 23
Relational operators
Operator Description

Check whether element of the first vector is greater


> than corresponding element of second vector

Check whether element of the first vector is less than


< corresponding element of second vector

Check whether element of the first vector is equal to


== corresponding element of second vector
Check whether element of the first vector is greater
<= than or equal to corresponding element of second
vector
Check whether element of the first vector is less than
>= or equal to corresponding element of second vector
Check whether element of the first vector is unequal to
!= corresponding element of second vector
Statistics using R 24
Logical operators
Operator Description

Element-wise Logical AND operator


&
Element-wise Logical OR operator
|
Logical NOT operator
!

Statistics using R 25
Other operators
Operator Description

Colon operator, used for sequence


:
This operator is used to identify if an element belongs
%in% to a vector

Used for Matrix multiplication


%*%

Statistics using R 26
Subset function of R
• Subset function is used to select the wanted
rows from the data frame
• Subset function is used to select the required
columns from the data frame

Use of [] in R
• Select the required variables or rows or
elements of given vector or matrix or data
frame
Statistics using R 27
Basic functions of R
Function Usage

help() Used to know information about a topic


? Used to know information about a topic
data() To list all the inbuilt data sets in R
date() To print the today date
q() To quit the R workspace
ls() List of objects created
args() To know the arguments of a particular
function
substr(x, start=n1, Extract the substring in a character vector
start=n2)
Statistics using R 28
Basic functions of R
Function Usage

append() To combine elements to a vector


length() No. of elements in vector
rbind() Combine vectors by row
cbind() Combine vectors by column
identical() Test if 2 objects are exactly equal
range() Minimum and maximum
rev() Elements in reverse order
sort() Sorting the vector
rep(x, n) Repeat the object x, n times
head() List of top lines of a object
Statistics using R 29
Basic functions of R
Function Usage

tail() Last part of object


seq(x,y, n) Sequence of numbers from x to y spaced
by n
Order(x) List the sorted element numbers of x
tolower() Convert string to lower case letters
toupper() Convert string to upper case letters
round() Round the numeric value
ceiling() Round the number to next highest integer
floor() Round the number to previous lowest
integer
Statistics using R 30
Basic functions of R
Function Usage

month.name Full names of months


month.abb Abbreviated names of month
letters Small alphabetic
LETTERS Capital alphabetic
remove() Removes the objects from the
environment
mode() Gives the type of variable
pi Constant value
str() Data structure of each variable in a data
frame
paste() To concatenate strings
Statistics using R 31
Math & Stat functions of R
Function Usage

abs() Absolute value of a object


sqrt() Square root of objects
log(x) Logarithm value of X base e
log10(x) Logarithm value of X base 10
log(x, base=y) Logarithm value of X base y
exp(x) Exponential value of x
cospi(x), sinpi(x), Gives the value of cos(pi*x), sin(pi*x),
tanpi(x) tan(pi*x)
factorial() Gives the factorial value
choose(x, y) Returns the number of possible
combinations
Statistics using R 32
Math & Stat functions of R
Function Usage

%*% Matrix multiplication


t() Transpose of a matrix
det() Determinant of a matrix
solve() Inverse of a matrix
eigen() Eigen values, Eigen vectors of matrix
unique() Removes duplicate value from vector
union() Union of two vectors
intersect() Intersection of two events
setdiff() Difference of sets
setequal() Check whether the sets are equal or not
Statistics using R 33
Math & Stat functions of R
Function Usage

mean() Gives the mean of the vector


median() Returns the median of the vector
min() Minimum value of the vector
max() Maximum value of the vector
sum() Gives the total of the vector
sd(x) Standard deviation of x
var(x) Returns the variance of x
quantile() Returns the quartiles, percentiles
scale() Returns z-scores
rank(x) Ranks of numbers in increasing order
Statistics using R 34
Math & Stat functions of R
Function Usage

rank(-x) Ranks of numbers in decreasing order


cumsum(x) Cumulative sum of vector
cumprod(x) Cumulative products of a vector
summary() Gives summary of the vector
sample() Creates sample from a vector
cov() Covariance of two or more vectors

Statistics using R 35
Plots in R
• Histogram

Important arguments in histogram plot


col –color for the bars of histogram
border – border color
main – Title of chart
xlab- Title of X-axis
ylab – Title of Y-axis

Statistics using R 36
• Stem &leaf plot

stem(x), where x is a vector

Statistics using R 37
• BOXPLOT

Important arguments in histogram plot

horizontal – TRUE or FALSE


col –color for the plot
border – border color
main – Title of chart
xlab- Title of X-axis
ylab – Title of Y-axis

Statistics using R 38
• Pie chart

Important arguments
labels – gives labels to the pie parts
radius – takes input of radius
clockwise- T or F
col- colors of parts
border – color of border
main- returns the title of the chart

Statistics using R 39
INTRODUCTION TO R

R is a free open software and programming language which is used for statistical analysis and
graphics. It has wide range of statistical tools and drawing tools which are useful in analyzing
the data. Since R is free software it can be downloaded (version 4.1.1).Basically this software
helps us to analyze the large data. Moreover many companies like Google, Twitter and
Microsoft are making use of this software to analyze the data

DATA TYPES
1. Using R commands
a. Assign 3.14 to a variable x and find its class name.
>x=3.14
>x
[1]3.14
>class(x)
[1]”numeric”

Statistics using R 40
b. Assign 4 to a variable y as an integer and find its class name.
>y=as.integer(4)
>y
[1]4
>class(y)
[1]”integer”
>is.integer(y)
[1]TRUE

c. Assign 5.64 to variable y using as . integer and verify whether 5.64 is an integer or not.
>y=as.integer(5.64)
>y
[1]5
>class(y)
[1]“integer”
>is.integer(y)
[1] TRUE

Statistics using R 41
d. Assign 1+2i to a variable z and find its class name.
>z=1+2i
>z
[1]1+2i
>class(z)
[1] “complex”
e. Assign 12 and 6 to a variables x,y respectively then check whether x>y , and find
class name .
>x=12;y=6
>z=x>y
>z
[1]TRUE
>class(z)
[1] “logical”

Statistics using R 42
f. Assign NAG to a variable x and find its class .
>x=as. character(“NAG”)
>x
[1]”NAG”
>class(x)
[1] “character”
g. Assign 3.14 to a variable x using as. character and verify whether 3.14 is
character or not.
>x=as. character(3.14)
>x
[1] “3.14”
>class(x)
[1] “character”

Statistics using R 43
h. Combine two characters “JOE” and “SMITH” using R command.
>fname= “JOE” ;lname= “SMITH”
>paste(fname,lname)
[1] “JOE SMITH”
i. Find numeric value of TRUE.
>as. numeric(TRUE)
[1] 1
j. Find numeric value of FALSE.
>as. numeric(FALSE)
[1]0
k. Assign u=TRUE and v=FALSE, then operate and on u and v , or on u and v and
negation on u.
>u=TRUE;v=FALSE
>u&v
[1]FALSE
>u|v
[1]TRUE
>!u
[1]FALSE

Statistics using R 44
Vector
A vector is a sequence of data elements of the same basic type. Members in a vector are
officially called components. Nevertheless, we will just call them members in this site.
Here is a vector containing three numeric values 2, 3 and 5.
> c(2, 3, 5)
[1] 2 3 5
And here is a vector of logical values.
> c(TRUE, FALSE, TRUE, FALSE, FALSE)
[1] TRUE FALSE TRUE FALSE FALSE
A vector can contain character strings.
> c("aa", "bb", "cc", "dd", "ee")
[1] "aa" "bb" "cc" "dd" "ee"
Incidentally, the number of members in a vector is given by the length function.
> length(c("aa", "bb", "cc", "dd", "ee"))
[1] 5
Statistics using R 45
• Combining Vectors

• Vector Arithmetics

• Vector Index

• Numeric Index Vector

• Logical Index Vector

• Named Vector Members

Statistics using R 46
Combining Vectors
Vectors can be combined via the function c. For examples, the following two vectors n and s
are combined into a new vector containing elements from both vectors.
> n = c(2, 3, 5)
> s = c("aa", "bb", "cc", "dd", "ee")
> c(n, s)
[1] "2" "3" "5" "aa" "bb" "cc" "dd" "ee"

Value Coercion
In the code snippet above, notice how the numeric values are being coerced into character
strings when the two vectors are combined. This is necessary so as to maintain the same
primitive data type for members in the same vector.

Statistics using R 47
Vector Arithmetic’s
Arithmetic operations of vectors are performed member-by-member, i.e., memberwise.
For example, suppose we have two vectors a and b.
> a = c(1, 3, 5, 7)
> b = c(1, 2, 4, 8)

Then, if we multiply a by 5, we would get a vector with each of its members multiplied by 5.
>5*a
[1] 5 15 25 35
And if we add a and b together, the sum would be a vector whose members are the sum of the
corresponding members from a and b.
>a+b
[1] 2 5 9 15
Similarly for subtraction, multiplication and division, we get new vectors via memberwise
operations.
>a-b
[1] 0 1 1 -1

Statistics using R 48
>a*b
[1] 1 6 20 56

>a/b
[1] 1.000 1.500 1.250 0.875

Recycling Rule
If two vectors are of unequal length, the shorter one will be recycled in order to match the
longer vector. For example, the following vectors u and v have different lengths, and their sum
is computed by recycling values of the shorter vector u.
> u = c(10, 20, 30)
> v = c(1, 2, 3, 4, 5, 6, 7, 8, 9)
>u+v
[1] 11 22 33 14 25 36 17 28 39

Statistics using R 49
Vector Index
We retrieve values in a vector by declaring an index inside a single square bracket "[]" operator.
For example, the following shows how to retrieve a vector member. Since the vector index is 1-
based, we use the index position 3 for retrieving the third member.
> s = c("aa", "bb", "cc", "dd", "ee")
> s[3]
[1] "cc"

Unlike other programming languages, the square bracket operator returns more than just
individual members. In fact, the result of the square bracket operator is another vector, and s[3]
is a vector slice containing a single member "cc".
Negative Index
If the index is negative, it would strip the member whose position has the same absolute value as
the negative index. For example, the following creates a vector slice with the third member
removed.
> s[-3]
[1] "aa" "bb" "dd" "ee"

Out-of-Range Index
If an index is out-of-range, a missing value will be reported via the symbol NA.
> s[10] Statistics using R 50
[1] NA
Numeric Index Vector
A new vector can be sliced from a given vector with a numeric index vector, which consists of
member positions of the original vector to be retrieved.
Here it shows how to retrieve a vector slice containing the second and third members of a given
vector s.
> s = c("aa", "bb", "cc", "dd", "ee")
> s[c(2, 3)]
[1] "bb" "cc"

Duplicate Indexes
The index vector allows duplicate values. Hence the following retrieves a member twice in one
operation.
> s[c(2, 3, 3)]
[1] "bb" "cc" "cc"

Statistics using R 51
Out-of-Order Indexes
The index vector can even be out-of-order. Here is a vector slice with the order of first and
second members reversed.
> s[c(2, 1, 3)]
[1] "bb" "aa" "cc"

Range Index
To produce a vector slice between two indexes, we can use the colon operator ":". This can
be convenient for situations involving large vectors.
> s[2:4]
[1] "bb" "cc" "dd"

More information for the colon operator is available in the R documentation.


> help(":")

Statistics using R 52
Logical Index Vector
A new vector can be sliced from a given vector with a logical index vector, which has the same
length as the original vector. Its members are TRUE if the corresponding members in the
original vector are to be included in the slice, and FALSE if otherwise.
For example, consider the following vector s of length 5.
> s = c("aa", "bb", "cc", "dd", "ee")
To retrieve the the second and fourth members of s, we define a logical vector L of the same
length, and have its second and fourth members set as TRUE.
> L = c(FALSE, TRUE, FALSE, TRUE, FALSE)
> s[L]
[1] "bb" "dd"
The code can be abbreviated into a single line.
> s[c(FALSE, TRUE, FALSE, TRUE, FALSE)]
[1] "bb" "dd"

Statistics using R 53
Named Vector Members
We can assign names to vector members.
For example, the following variable v is a character string vector with two members.
> v = c("Mary", "Sue")
>v
[1] "Mary" "Sue"
We now name the first member as First, and the second as Last.
> names(v) = c("First", "Last")
>v
First Last
"Mary" "Sue"
Then we can retrieve the first member by its name.
> v["First"]
[1] "Mary"

Statistics using R 54
Furthermore, we can reverse the order with a character string index vector.
> v[c("Last", "First")]
Last First
"Sue" "Mary"

Statistics using R 55
Matrix
A matrix is a collection of data elements arranged in a two-dimensional rectangular layout. The
following is an example of a matrix with 2 rows and 3 columns.

We reproduce a memory representation of the matrix in R with the matrix function. The data
elements must be of the same basic type.
> A = matrix(
+ c(2, 4, 3, 1, 5, 7), # the data elements
+ nrow=2, # number of rows
+ ncol=3, # number of columns
+ byrow = TRUE) # fill matrix by rows

>A # print the matrix


[,1] [,2] [,3]
[1,] 2 4 3
[2,] 1 5 7

Statistics using R 56
An element at the mth row, nth column of A can be accessed by the expression A[m, n].
> A[2, 3] # element at 2nd row, 3rd column
[1] 7
The entire mth row A can be extracted as A[m, ].
> A[2, ] # the 2nd row
[1] 1 5 7
Similarly, the entire nth column A can be extracted as A[ ,n].
> A[ ,3] # the 3rd column
[1] 3 7
We can also extract more than one rows or columns at a time.
> A[ ,c(1,3)] # the 1st and 3rd columns
[,1] [,2]
[1,] 2 3
[2,] 1 7

Statistics using R 57
If we assign names to the rows and columns of the matrix, than we can access the elements by
names.
> dimnames(A) = list(
+ c("row1", "row2"), # row names
+ c("col1", "col2", "col3")) # column names

>A # print A
col1 col2 col3
row1 2 4 3
row2 1 5 7

> A["row2", "col3"] # element at 2nd row, 3rd column


[1] 7

Statistics using R 58
Matrix Construction
There are various ways to construct a matrix. When we construct a matrix directly with data
elements, the matrix content is filled along the column orientation by default. For example, in
the following code snippet, the content of B is filled along the columns consecutively.
> B = matrix(
+ c(2, 4, 3, 1, 5, 7),
+ nrow=3,
+ ncol=2)

>B # B has 3 rows and 2 columns


[,1] [,2]
[1,] 2 1
[2,] 4 5
[3,] 3 7

Statistics using R 59
Transpose
We construct the transpose of a matrix by interchanging its columns and rows with the function
t.
> t(B) # transpose of B
[,1] [,2] [,3]
[1,] 2 4 3
[2,] 1 5 7

Statistics using R 60
Combining Matrices
The columns of two matrices having the same number of rows can be combined into a larger
matrix. For example, suppose we have another matrix C also with 3 rows.
> C = matrix(
+ c(7, 4, 2),
+ nrow=3,
+ ncol=1)

>C # C has 3 rows


[,1]
[1,] 7
[2,] 4
[3,] 2
Then we can combine the columns of B and C with cbind.
> cbind(B, C)
[,1] [,2] [,3]
[1,] 2 1 7
[2,] 4 5 4
[3,] 3 7 2

Statistics using R 61
Similarly, we can combine the rows of two matrices if they have the same number of columns
with the rbind function.
> D = matrix(
+ c(6, 2),
+ nrow=1,
+ ncol=2)

>D # D has 2 columns


[,1] [,2]
[1,] 6 2

> rbind(B, D)
[,1] [,2]
[1,] 2 1
[2,] 4 5
[3,] 3 7
[4,] 6 2

Statistics using R 62
Deconstruction
We can deconstruct a matrix by applying the c function, which combines all column vectors
into one.
> c(B)
[1] 2 4 3 1 5 7

Statistics using R 63
List
A list is a generic vector containing other objects.
For example, the following variable x is a list containing copies of three vectors n, s, b, and a
numeric value 3.
> n = c(2, 3, 5)
> s = c("aa", "bb", "cc", "dd", "ee")
> b = c(TRUE, FALSE, TRUE, FALSE, FALSE)
> x = list(n, s, b, 3) # x contains copies of n, s, b
List Slicing
We retrieve a list slice with the single square bracket "[]" operator. The following is a slice
containing the second member of x, which is a copy of s.
> x[2]
[[1]]
[1] "aa" "bb" "cc" "dd" "ee"
With an index vector, we can retrieve a slice with multiple members. Here a slice containing the
second and fourth members of x.
> x[c(2, 4)]
[[1]]
[1] "aa" "bb" "cc" "dd" "ee"
[[2]]
[1] 3
Statistics using R 64
Member Reference
In order to reference a list member directly, we have to use the double square bracket "[[]]"
operator. The following object x[[2]] is the second member of x. In other words, x[[2]] is a
copy of s, but is not a slice containing s or its copy.
> x[[2]]
[1] "aa" "bb" "cc" "dd" "ee"

We can modify its content directly.


> x[[2]][1] = "ta"
> x[[2]]
[1] "ta" "bb" "cc" "dd" "ee"
>s
[1] "aa" "bb" "cc" "dd" "ee" # s is unaffected

Statistics using R 65
Named List Members
We can assign names to list members, and reference them by names instead of numeric
indexes.
For example, in the following, v is a list of two members, named "bob" and "john".
> v = list(bob=c(2, 3, 5), john=c("aa", "bb"))
>v
$bob
[1] 2 3 5

$john
[1] "aa" "bb"

Statistics using R 66
List Slicing
We retrieve a list slice with the single square bracket "[]" operator. Here is a list slice containing
a member of v named "bob".
> v["bob"]
$bob
[1] 2 3 5

With an index vector, we can retrieve a slice with multiple members. Here is a list slice with
both members of v. Notice how they are reversed from their original positions in v.
> v[c("john", "bob")]
$john
[1] "aa" "bb"

$bob
[1] 2 3 5

Statistics using R 67
Member Reference
In order to reference a list member directly, we have to use the double square bracket "[[]]"
operator. The following references a member of v by name.
> v[["bob"]]
[1] 2 3 5
A named list member can also be referenced directly with the "$" operator in lieu of the
double square bracket operator.
> v$bob
[1] 2 3 5
Search Path Attachment
We can attach a list to the R search path and access its members without explicitly
mentioning the list. It should to be detached for cleanup.
> attach(v)
> bob
[1] 2 3 5
> detach(v)

Statistics using R 68
Data Frame
A data frame is used for storing data tables. It is a list of vectors of equal length. For example,
the following variable df is a data frame containing three vectors n, s, b.
> n = c(2, 3, 5)
> s = c("aa", "bb", "cc")
> b = c(TRUE, FALSE, TRUE)
> df = data.frame(n, s, b) # df is a data frame
Build-in Data Frame
We use built-in data frames in R for our tutorials. For example, here is a built-in data frame in
R, called mtcars.
> mtcars
mpg cyl disp hp drat wt ...
Mazda RX4 21.0 6 160 110 3.90 2.62 ...
Mazda RX4 Wag 21.0 6 160 110 3.90 2.88 ...
Datsun 710 22.8 4 108 93 3.85 2.32 ...
............

Statistics using R 69
The top line of the table, called the header, contains the column names. Each horizontal line
afterward denotes a data row, which begins with the name of the row, and then followed by the
actual data. Each data member of a row is called a cell.
To retrieve data in a cell, we would enter its row and column coordinates in the single square
bracket "[]" operator. The two coordinates are separated by a comma. In other words, the
coordinates begins with row position, then followed by a comma, and ends with the column
position. The order is important.
Here is the cell value from the first row, second column of mtcars.
> mtcars[1, 2]
[1] 6
Moreover, we can use the row and column names instead of the numeric coordinates.
> mtcars["Mazda RX4", "cyl"]
[1] 6

Statistics using R 70
Lastly, the number of data rows in the data frame is given by the nrow function.
> nrow(mtcars) # number of data rows
[1] 32
And the number of columns of a data frame is given by the ncol function.
> ncol(mtcars) # number of columns
[1] 11
Further details of the mtcars data set is available in the R documentation.
> help(mtcars)
Preview
Instead of printing out the entire data frame, it is often desirable to preview it with the head
function beforehand.
> head(mtcars)
mpg cyl disp hp drat wt ...
Mazda RX4 21.0 6 160 110 3.90 2.62 ...
............

Statistics using R 71
VECTORS USING R
1. Using R command
a. Create a vector of numeric values 3,4,5,6 and store it in m.
>m=c(3,4,5,6)
a. Create a vector of logical values TRUE,FALSE,TRUE,FALSE,FALSE and store it in n.
>n=c(TRUE,FALSE,TRUE,FALSE,FALSE)
a. Create a vector of character strings aa,bb,cc,dd,ee and store it in s.
>s=c(“aa”, “bb”, “cc”, “dd”, “ee”)
a. Combine vector m and s
>c(m, s)

Statistics using R 72
2. Write R command for the following
a. Create vectors p=(2, 3,4,5) and q=(4,6,8,9)
>p=c(2,3,4,5)
>q=c(4,6,8,9)
b. Addition of p and q
>p + q
c. Subtract p from q
>q-p
d. Product of p and q
>p*q
e. 5p+6q
>5*p+6*q
f. Divide p by q
>p/q
g. length of p
>length(p)
h. combine vector p and q
>c(p ,q)

Statistics using R 73
3. create a vector g with elements from 1:10 using R and then
>g=c(1,2,3,4,5,6,7,8,9,10) or g=1:10 or g=seq(1,10)
a. extract 2𝑛𝑑 𝑒𝑙𝑒𝑚𝑒𝑛𝑡 from g
>g[2]
b. delete 4𝑡ℎ 𝑒𝑙𝑒𝑚𝑒𝑛𝑡 𝑓𝑟𝑜𝑚 𝑔
>g[-4]
c. extract 6𝑡ℎ 𝑎𝑛𝑑 8𝑡ℎ 𝑒𝑙𝑒𝑚𝑒𝑛𝑡𝑠 𝑓𝑟𝑜𝑚 𝑔
>g[c(6,8)]
d. extract 8𝑡ℎ 𝑒𝑙𝑒𝑚𝑒𝑛𝑡 from g
>g[8]
e. delete 4𝑡ℎ 𝑎𝑛𝑑 5𝑡ℎ elements from g
>g[c(-4,-5)

Statistics using R 74
4. using R command,
a. Create a vector x with elements 4,9,16,25,36,49 and then create matrix y by finding
square root of vector x using R ,then find mean and median of y.
>x=c(4,9,16,25,36,49)
>y=sqrt(x)
>mean(y)
>median(y)
b. create a vector z with element ab, cd, ef, gh, ij, kl, mn using R and then find vector slice
between 2:5.
>z=c(“ab”, “cd”, “ef”, “gh”, “ij” , “kl”, “mn”)
>z[2:5]
c. Create vector u=(10,12,13) and v=(1,2,3,4,5,6,7,8,9) and then find u+v.
>u=c(10,12,13)
>v=c(1,2,3,4,5,6,7,8,9)
>u+v

Statistics using R 75
Statistics using R 76

You might also like