Lab3-Lists, Matrices and Arrays
Lab3-Lists, Matrices and Arrays
[[2]]
[1] TRUE
[[3]]
[1] FALSE
> length(s)
[1] 3
$b
[1] "red" "blue"
$d
[1] TRUE FALSE TRUE
•
Exercise:
Create a list named ls. The list ls contains following 6 vectors with their values as follows :
• Rollno- 1:4
• First name- Ravi,Om,Ajay,Shiv
• Last name-Dev,Gandhi,Pande,Rao
• Subject-AE,DS,ML,OS
• Marks-35,40,38,02
• Result –P,P,P,F.
##Task To be performed:
1. Print the list ls.
2. Print all the independent element of list ls.
3. Find the class of element of the list.
4. Print(ls[[2]][1])
5. Print(ls[[4]][4])
6. Print(ls[5])
7. It was found that the marks of Ajay were entered wrongly. The correct marks should be 45. Replace the marks of Ajay
without disturbing the other elements or without loading the complete list again.
8. 8. the subject name of OS to OE. Modify the required element only.
9. 9. It was decided that the data base should also have native place information. Ravi stays at Pune, Ajay at Mumbai, Shiv
at Nashik and Om at Nagpur. Please add this information also in the list.
10. 10.Add one more student information names Julie Gommes. The marks obtained by Julie in subject DS is 30 and the
result is P. Her native place is Hyderabad.
MATRICES
Matrices are the R objects where the elements are arranged in two dimensional formats. It contains rows and
columns. The elements are of same type. Matrices are vectors with “dimension” attribute. The dimension
attribute itself is a integer vector of length 2 (number of rows and number of columns).
>d<-c(2,5,6)
> e<-c(9,5,5)
> m<-matrix(c(d,e),2,3)
> m
[,1] [,2] [,3]
[1,] 2 6 5
[2,] 5 9 5
2. Dimension Attribute:
Matrix can be created by adding dimension attribute as follows:
>d<-1:8
> dim(d)<-c(2,4) ## Considers rows as 2 and columns as 4.
> print(d)
[,1] [,2] [,3] [,4]
[1,] 1 3 5 7
[2,] 2 4 6 8
> dim(d) ## It retrieves the assigned values of dimension.
[1] 2 4
ARRAYS
Arrays are the R data objects which can store data in more than two dimensions.
Creating Arrays:
If we create an array of dimension (3, 4, 2) then it creates 2 rectangular matrices each with 3 rows and 4
columns. 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.
> v1<-c(1,3,5)
> v2<-c(2,4)
> v3<-c(9,10,11,19)
> a1<-array(c(v1,v2,v3),dim=c(3,3,2))
> a1
, , 1
, , 2
Accessing Array:
Like matrix you can access either single element or complete row or complete column of any of the matrices.
For example:
>d<-a1[2,3,1] ## It gives 2nd row and third column element of 1st matrix
[1] 11
> f<-a1[2,2,] ## It gives 2nd row 2nd column element of both the matrices.
> h<-a1[2,,] ## It gives 2nd row all columns and all matrix data.
Array Operations:
Different arithmetic operations can be done on elements of arrays in the similar fashion as of matrices.