Author: Team BioSakshat

Last update: June 2017

Copyright © 2017 BioSakshat, Inc. All rights reserved.

.

An R list is an object consisting of an ordered collection of objects known as its components.

x1=1:5; # vector
x2=matrix(1:20, ncol=5);
x3= data.frame(1:5, letters[1:5]);
mylist = list(comp1=x1, comp2=x2, comp3=x3);
mylist;
## $comp1
## [1] 1 2 3 4 5
## 
## $comp2
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    5    9   13   17
## [2,]    2    6   10   14   18
## [3,]    3    7   11   15   19
## [4,]    4    8   12   16   20
## 
## $comp3
##   X1.5 letters.1.5.
## 1    1            a
## 2    2            b
## 3    3            c
## 4    4            d
## 5    5            e

Access component of list using $ notation

# Access componene1 using $ notation
mylist$comp1;
## [1] 1 2 3 4 5
mylist$comp2;
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    5    9   13   17
## [2,]    2    6   10   14   18
## [3,]    3    7   11   15   19
## [4,]    4    8   12   16   20

Access component of list using []

Using [] returns list while using [[]] returns the component.

# Fetching 2nd component using []. Returns list
m1 = mylist[2];
# Fetching 2nd component using [[]]. Returns matrix
m2 = mylist[[2]];
m1;
## $comp2
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    5    9   13   17
## [2,]    2    6   10   14   18
## [3,]    3    7   11   15   19
## [4,]    4    8   12   16   20
str(m1);
## List of 1
##  $ comp2: int [1:4, 1:5] 1 2 3 4 5 6 7 8 9 10 ...
m2;
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    5    9   13   17
## [2,]    2    6   10   14   18
## [3,]    3    7   11   15   19
## [4,]    4    8   12   16   20
str(m2);
##  int [1:4, 1:5] 1 2 3 4 5 6 7 8 9 10 ...