Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R paste matrix cells together

Tags:

r

I want to paste cells of matrix together, But when I do paste(),It returns a vector. Is there a direct function for same in R?

mat <- matrix(1:4,2,2)
paste(mat,mat,sep=",")

I want the output as

     [,1] [,2]
[1,]  1,1  2,2
[2,]  3,3  4,4
like image 561
anonR Avatar asked Dec 11 '22 18:12

anonR


2 Answers

A matrix in R is just a vector with an attribute specifying the dimensions. When you paste them together you are simply losing the dimension attribute.

So,

matrix(paste(mat,mat,sep=","),2,2)

Or, e.g.

mat1 <- paste(mat,mat,sep=",")
> mat1
[1] "1,1" "2,2" "3,3" "4,4"
> dim(mat1) <- c(2,2)
> mat1
     [,1]  [,2] 
[1,] "1,1" "3,3"
[2,] "2,2" "4,4"

Here's just one example of how you might write a simple function to do this:

paste_matrix <- function(...,sep = " ",collapse = NULL){
    n <- max(sapply(list(...),nrow))
    p <- max(sapply(list(...),ncol))

    matrix(paste(...,sep = sep,collapse = collapse),n,p)
}

...but the specific function you want will depend on how you want it to handle more than two matrices, matrices of different dimensions or possibly inputs that are totally unacceptable (random objects, NULL, etc.).

This particular function recycles the vector and outputs a matrix with the dimension matching the largest of the various inputs.

like image 176
joran Avatar answered Dec 22 '22 00:12

joran


Another approach to the Joran's one is to use [] instead of reconstructing a matrix. In that way you can also keep the colnames for example:

truc <- matrix(c(1:3, LETTERS[3:1]), ncol=2)
colnames(truc) <- c("A", "B")
truc[] <- paste(truc, truc, sep=",")
truc
#      A     B    
# [1,] "1,1" "C,C"
# [2,] "2,2" "B,B"
# [3,] "3,3" "A,A"
like image 42
Bastien Avatar answered Dec 21 '22 22:12

Bastien