Converting R matrix into LaTeX matrix in the math or equation environment

后端 未结 3 805
轻奢々
轻奢々 2020-12-15 12:38

Let\'s say there is an R matrix x:

x <- structure(c(2, 3, 5, 7, 9, 12, 17, 10, 18, 13), .Dim = c(5L,2L), .Dimnames = list(NULL, c(\"X1\", \"X         


        
3条回答
  •  青春惊慌失措
    2020-12-15 13:04

    if anyone needs rounded matrices with borders via \bordermatrix, I appended @Maxim.K's function to that end.

    m2l <- function(matr) {
        matr <- round(x = matr, digits = 2)  # sadly this is necessary because given this function, the options(digits = 2) does not work
        matr2 <- data.frame(c("~",rownames(matr)))  # add rownames
        for (r in colnames(matr)) {  # add col contents and colnames
          matr2 <- cbind(matr2, c(r, matr[,r]))
        }
        printmrow <- function(x) {
            ret <- paste(paste(x, collapse = " & "), "\\cr")
            sprintf(ret)
        }
        out <- apply(matr2, 1, printmrow)
        out2 <- paste("\\bordermatrix{", paste(out, collapse = ' '),"}")
        return(out2)
    }
    

    Pretty hideous code, I know, but get's the job done.

    Maybe this'll be useful for someone out there.

    Can look nice, especially for correlation matrices and such stuff:

    tex

提交回复
热议问题