6

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
anonR
  • 849
  • 7
  • 26

4 Answers4

11

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.

joran
  • 169,992
  • 32
  • 429
  • 468
  • Yeah, I understand that. But wanted to know if there is an function in R for pasting cells together without loosing the dimensional attribute. Like we can add matrices and subtract without loosing the dimensional attribute . – anonR Feb 23 '16 at 21:57
  • @anonR Well, my answer illustrates how you'd write one, no...? (With some checking on the suitability of inputs and dimensions.) – joran Feb 23 '16 at 21:58
  • 6
    @anonR - you could do `mat[] <- paste(mat, mat, sep = ",")` but that overwrites the original `mat` – Rich Scriven Feb 23 '16 at 21:58
3

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"
Bastien
  • 31
  • 1
2

Or use sprintf withdim<-

`dim<-`(sprintf('%d,%d', mat, mat), dim(mat))
#      [,1]  [,2] 
#[1,] "1,1" "3,3"
#[2,] "2,2" "4,4"
akrun
  • 874,273
  • 37
  • 540
  • 662
0

The ascii library has a function paste.matrix for element-wise paste across matrices. The output is the transpose to the desired outcome, but that's easy to address with t().

library(ascii)
mat <- matrix(1:4,2,2)
t(paste.matrix(mat,mat,sep=","))
     [,1]  [,2] 
[1,] "1,1" "2,2"
[2,] "3,3" "4,4"
MBorg
  • 1,345
  • 2
  • 19
  • 38