These exercises are about the Lists sections of Introduction to R.

Exercise 1

firstElement <- c("A","B","C","D","E")
secondElement <- matrix(1:5,nrow=5,ncol=5)
thirdElement <- data.frame(Sample=c("Sample1","Sample2","Sample3","Sample4"), Age=c(25,21,24,25),factor=c("Smoker","Smoker","NonSmoker","Smoker"))

my_list <- list(firstElement, secondElement, thirdElement)
my_list
## [[1]]
## [1] "A" "B" "C" "D" "E"
## 
## [[2]]
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    1    1    1    1
## [2,]    2    2    2    2    2
## [3,]    3    3    3    3    3
## [4,]    4    4    4    4    4
## [5,]    5    5    5    5    5
## 
## [[3]]
##    Sample Age    factor
## 1 Sample1  25    Smoker
## 2 Sample2  21    Smoker
## 3 Sample3  24 NonSmoker
## 4 Sample4  25    Smoker
names(my_list) <- c("my_vector", "my_matrix", "my_df")
my_list
## $my_vector
## [1] "A" "B" "C" "D" "E"
## 
## $my_matrix
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    1    1    1    1
## [2,]    2    2    2    2    2
## [3,]    3    3    3    3    3
## [4,]    4    4    4    4    4
## [5,]    5    5    5    5    5
## 
## $my_df
##    Sample Age    factor
## 1 Sample1  25    Smoker
## 2 Sample2  21    Smoker
## 3 Sample3  24 NonSmoker
## 4 Sample4  25    Smoker
my_list$my_df$Age
## [1] 25 21 24 25
my_list[[3]][,2]
## [1] 25 21 24 25
fourthElement <- list(1:5,
                      2:6)

my_list <- c(my_list,list(fourthElement ))
length(my_list)
## [1] 4
my_list[[4]][[2]]
## [1] 2 3 4 5 6
my_list <- list(First=c(5,2,9),Second=c(13,12,6),Third=c(1,3,4))
flat_list <- unlist(my_list)
listAsMat <- matrix(flat_list,
                    nrow=length(my_list),
                    ncol=3,
                    byrow=T,
                    dimnames=list(names(my_list)))
listAsMat
##        [,1] [,2] [,3]
## First     5    2    9
## Second   13   12    6
## Third     1    3    4