Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
How to convert a matrix column into list in R?
To convert a matrix column into list can be done by using the apply function. We will have to read the columns of the matrix as list by using as.list function. For example, if we have a matrix called M then the columns in M can be converted into list by using the command apply(M,2,as.list).
Example1
> M1<-matrix(rnorm(10),ncol=2) > M1
Output
[,1] [,2] [1,] -1.3256074 -0.07328026 [2,] 1.1997584 -1.06542989 [3,] -0.2214659 -1.75903298 [4,] 1.4446361 -0.12859397 [5,] -0.1504967 0.97264445
Converting M1 columns to a list −
> apply(M1,2,as.list)
Output
[[1]] [[1]][[1]] [1] -1.325607 [[1]][[2]] [1] 1.199758 [[1]][[3]] [1] -0.2214659 [[1]][[4]] [1] 1.444636 [[1]][[5]] [1] -0.1504967 [[2]] [[2]][[1]] [1] -0.07328026 [[2]][[2]] [1] -1.06543 [[2]][[3]] [1] -1.759033 [[2]][[4]] [1] -0.128594 [[2]][[5]] [1] 0.9726444
Example2
> M2<-matrix(rpois(10,5),ncol=2) > M2
Output
[,1] [,2] [1,] 4 7 [2,] 6 7 [3,] 2 4 [4,] 7 2 [5,] 8 1
Converting M2 columns to a list −
> apply(M2,2,as.list)
Output
[[1]] [[1]][[1]] [1] 4 [[1]][[2]] [1] 6 [[1]][[3]] [1] 2 [[1]][[4]] [1] 7 [[1]][[5]] [1] 8 [[2]] [[2]][[1]] [1] 7 [[2]][[2]] [1] 7 [[2]][[3]] [1] 4 [[2]][[4]] [1] 2 [[2]][[5]] [1] 1
Example3
> M3<-matrix(sample(c("true","false"),10,replace=TRUE),ncol=2)
> M3
Output
[,1] [,2] [1,] "true" "false" [2,] "false" "true" [3,] "true" "false" [4,] "false" "true" [5,] "false" "false"
Converting M3 columns to a list −
> apply(M3,2,as.list)
Output
[[1]] [[1]][[1]] [1] "true" [[1]][[2]] [1] "false" [[1]][[3]] [1] "true" [[1]][[4]] [1] "false" [[1]][[5]] [1] "false" [[2]] [[2]][[1]] [1] "false" [[2]][[2]] [1] "true" [[2]][[3]] [1] "false" [[2]][[4]] [1] "true" [[2]][[5]] [1] "false"
Advertisements
