问题
I got a list of matrices X rows by 2 columns, called list_of_matrices_by2
list_of_matrices_by2[1:3]
[[1]]
[,1] [,2]
[1,] "7204" "d"
[2,] "7204" "a"
[[2]]
[,1] [,2]
[1,] "2032" "b"
[2,] "2032" "e"
[3,] "2032" "a"
[[3]]
[,1] [,2]
[1,] "802" "d"
[2,] "802" "b"
I want to stack all my matrices in a all_pairs matrix, so I did this
all_pairs=do.call(rbind,list_of_matrices_by2)
all_pairs[1:10]
[,1] [,2]
[1,] "7204" "d"
[2,] "7204" "a"
[3,] "2032" "b"
[4,] "2032" "e"
[5,] "2032" "a"
[6,] "802" "d"
[7,] "802" "b"
[8,] "4674" "c"
[9,] "4674" "a"
[10,] "3886" "b"
class(all_pairs)
[1] "matrix"
For some reason, I need the rows of this matrix to be of class matrix. But it shouldn't be a problem since rows of matrix are matrix in R, right. But no!
all_pairs[1,]
[[1]]
[1] "7204"
[[2]]
[1] "d
So here are my questions : 1) Why this? How come a row of a matrix can possibly be a list? 2) What would you do to make it work, i.e. each row of my matrix has to be a matrix?
回答1:
I am sure that your list_of_matrices_by2
is like:
x <- list(matrix(list("7204","7204","d","a"), ncol = 2),
matrix(list("2032","2032","2032","b","e","a"), ncol = 2),
matrix(list("802","802","d","b"), ncol = 2))
#[[1]]
# [,1] [,2]
#[1,] "7204" "d"
#[2,] "7204" "a"
#[[2]]
# [,1] [,2]
#[1,] "2032" "b"
#[2,] "2032" "e"
#[3,] "2032" "a"
#[[3]]
# [,1] [,2]
#[1,] "802" "d"
#[2,] "802" "b"
unlist(lapply(x, class))
# [1] "matrix" "matrix" "matrix"
unlist(lapply(x, mode))
# [1] "list" "list" "list"
So you do have a matrix, but it is not a matrix of list instead of numeric. You can perform rbind
as usual:
y <- do.call(rbind, x)
# [,1] [,2]
#[1,] "7204" "d"
#[2,] "7204" "a"
#[3,] "2032" "b"
#[4,] "2032" "e"
#[5,] "2032" "a"
#[6,] "802" "d"
#[7,] "802" "b"
It has class "matrix", but still with mode "list". That is why when you extract the first row you get a list:
y[1, ]
#[[1]]
#[1] "7204"
#[[2]]
#[1] "d"
I don't know how you obtain those matrices. If you can control the generation process, it would be good that you end up with matrices of numeric. If you can not control it, you need convert them manually as below:
x <- lapply(x, function (u) matrix(unlist(u), ncol = 2))
unlist(lapply(x, mode))
# [1] "character" "character" "character"
Then you can do
do.call(rbind, x)
Related:
- Why is this matrix not numeric?
- How to create a matrix of lists?
回答2:
Ok guys, I finally found a solution.
Reminder
all_pairs=do.call(rbind,list_of_matrices_by2)
Extraction of all values of my matrix into a vector
extracted_values=unlist(as.vector(t(all_pairs)))
Build the new matrix
all_pairs_new=t(matrix(data = extracted_values,nrow = 2,ncol = 10000))
来源:https://stackoverflow.com/questions/39292984/why-a-row-of-my-matrix-is-a-list-r