List and Array in R language

 In this post we will see various method of list and Array. In previous post we Saw about vector and matrix, I hope this will be also easy for you. Let's start.

List: We can say list and vector are pretty much similar but the only difference and the important one is that vector consist of same data element where as list consist of different types of data element. 

To create a list we use a function called list()

Here list take input from vector only but of different type at same time.

So, make it clear let's see the example:

Name<- c("Adam","Steve","Tom","Robert")

Rollno <-  c (1,2,3,4)

Mylist<- list(Name, Rollno)

print (Mylist)

Output:

               [1]  "Adam" "Steve" "Tom" "Robert"

               [1] 1 2 3 4 

So, Over here we tooked different type of data element in list via vector only,  but this functionality is not allowed in vector.

Array: Array is collection of data which can be printed different number of time as you wish, basically it's a type of matrix only but this print the same matrix different number of times.

- An array is created using a function called array(). It takes vector as input and uses the value in dim parameter to create an array

-Syntax of array is same as to create a matrix but the difference is there we take there function called as matrix and here we take array and one more difference is to define number of rows and columns and one more additional here how many time to repeat the matrix.

We use dim as dimensions.

-Syntax: dim=(nrow, ncol, repeatno.)

 There is one more dimnames which is used to name the rows and columns.

Example:  # program to create array

row=c("row1","row2")

colu=c("col1","col2","col3","col4")

mat=c("Matrix 1","Matrix 2","Matrix3")

a<array(c(1,2,3,4,5,6,7,8),dim=c(2,4,3),dimnames=

list(row,colu,mat))

print(a)


, , Matrix 1

     col1 col2 col3 col4
row1    1    3    5    7
row2    2    4    6    8

, , Matrix 2

     col1 col2 col3 col4
row1    1    3    5    7
row2    2    4    6    8

, , Matrix3

     col1 col2 col3 col4
row1    1    3    5    7
row2    2    4    6    8

Here in output you can see that we have named each rows and columns by using attribute ( dimnames) were dim takes input of number of rows, columns, and repeat number.

So, In the same manner dimnames take input of names of rows, columns, and repeated matrix name via list. 

Comments