R List

Lists are another kind of data storage in R. List do not have to be of the same type. List elements are accessed through indexing operations. There can be list(s) inside a List. List can be created using list() function.

R List Syntax:

list_name<-list(element1,element2,element3,list,....etc)

How to create a List in R:

> x<-list("empname"="George","empno"=1000,"salary"=10000) > x $empname [1] "George" $empno [1] 1000 $salary [1] 10000 > class(x) [1] "list"

List structure can be examined using str() function:

> str(x) List of 3 $ empname: chr "George" $ empno : num 1000 $ salary : num 10000

How to access List elements in R

> x #list x $empname [1] "George" $empno [1] 1000 $salary [1] 10000 > x[2] #2nd element of list $empno [1] 1000 > x[-2] #exclude 2 element of list x $empname [1] "George" $salary [1] 10000 > x[2:3] # List range from 2 to 3 $empno [1] 1000 $salary [1] 10000

> y<-list("Apple","Mango",matrix(c(1,2,4,2,5,3), nrow=3),TRUE) > y [[1]] [1] "Apple" [[2]] [1] "Mango" [[3]] [,1] [,2] [1,] 1 2 [2,] 2 5 [3,] 4 3 [[4]] [1] TRUE > names(y)<-c("k","l","m") #Assign names to elements in the list > y$m # value of m [,1] [,2] [1,] 1 2 [2,] 2 5 [3,] 4 3 > y$m[2,2] #To get matrix of 2 2 row and 2dn column of list 3rd element. [1] 5 > y$l [1] "Mango"

List modification in R:

> y[1]<-"Grape" # Modify 1st elelement of list y > y [[1]] [1] "Grape" [[2]] [1] "Mango" [[3]] [,1] [,2] [1,] 1 2 [2,] 2 5 [3,] 4 3 [[4]] [1] TRUE

Merging Lists:

We can merge all lists into one list by placing all the lists inside list() function.

> x<-list(1:3) # Create two lists x and y > y<-list("Apple","Orange","Mango") > z=merged.list<-c(x,y) # Merge above two lists into new list z > z [[1]] [1] 1 2 3 [[2]] [1] "Apple" [[3]] [1] "Orange" [[4]] [1] "Mango"

Powered by WordPress