R paste matrix cells together

前端 未结 3 1557
醉酒成梦
醉酒成梦 2021-01-19 15:23

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)
past         


        
相关标签:
3条回答
  • 2021-01-19 15:54

    Or use sprintf withdim<-

    `dim<-`(sprintf('%d,%d', mat, mat), dim(mat))
    #      [,1]  [,2] 
    #[1,] "1,1" "3,3"
    #[2,] "2,2" "4,4"
    
    0 讨论(0)
  • 2021-01-19 16:04

    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.

    0 讨论(0)
  • 2021-01-19 16:04

    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"
    
    0 讨论(0)
提交回复
热议问题