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
## $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
## [1] 25 21 24 25
## [1] 25 21 24 25
## [1] 4
## [1] 2 3 4 5 6
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