Home > Mobile >  Print a matrix flattened by column using a separator
Print a matrix flattened by column using a separator

Time:10-14

I have the following matrix made from a vector of vectors, which I want to print separated by the & operator.

vec1 <-   c(1, 2, 3, 4)
vec2 <-  c(5, 6, 7, 8)
vec3 <-   c(9, 10, 11, 12)
vec4 <-  c(13, 14, 15, 16)
vec5 <-  c(17, 18, 19, 20)
vec6 <- c(21, 22, 23, 24)

 Mat <- matrix(c(vec1, vec2, vec3, vec4, vec5, vec6), nrow = 6, ncol = 4, byrow = TRUE)


(vect1 <- c(Mat[1,1], Mat[1,2], Mat[1,3], Mat[1,4], Mat[3,1], Mat[3,2], Mat[3,3], Mat[3,4], Mat[5,1], Mat[5,2], Mat[5,3], Mat[5,4]))

This is what I want for the above.

[1]  1 & 2 & 3 & 4 & 9 & 10 & 11 & 12 & 17 & 18 & 19 & 20

(vect2 <-  c(Mat[2,1], Mat[2,2], Mat[2,3], Mat[2,4], Mat[4,1], Mat[4,2], Mat[4,3], Mat[4,4], Mat[6,1], Mat[6,2], Mat[6,3], Mat[6,4]))

This is what I want for the above.

[1]  5 & 6 & 7 & 8 & 13 & 14 & 15 & 16 & 21 & 22 & 23 & 24

I actually need it in the output in the latex table such that the & symbol will separate each element from the other.

CodePudding user response:

c() is a convenient function to flatten matrices by column, so t() then c() flattens by row.

Mat |>
  t() |>
  c() |>
  paste(collapse = " & ")

"1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15 & 16 & 17 & 18 & 19 & 20 & 21 & 22 & 23 & 24"

Feel free to leave out the paste step if you do not require it in string format.

|> is the base R form of a pipe, if you are unfamiliar with it.

  • Related