在R中编写一个带有矩阵列表的文本文件

时间:2019-03-21 18:33:07

标签: r

我试图将一堆矩阵(不同维度)汇总到一个列表中,然后将该列表写入文本文件,每个矩阵之间都有换行符。这是一个虚拟的示例:

x <- matrix(0, nrow=2, ncol=7)
y <- matrix(0, nrow=7, ncol=7)
z <- matrix(0, nrow=4, ncol=7)
n_y <- t(matrix(nrow(allpar12), nrow(allpar12))) #just need a 1x2 matrix with the nrow(x) in each cell, this probably isn't the best way to do it.
test <- list(x, y, y, n_y, z)

lapply(test, cat, "\n", file="test.txt", append=T)

文本文件如下所示: output

似乎矩阵正在作为矢量打印。如何更改代码,使其以矩阵形式打印?

谢谢!

1 个答案:

答案 0 :(得分:0)

尝试

create_text <- function(m){
  res <- ""
  m <- formatC(m, width = max(nchar(trunc(m))), flag = "", format = "d")
  for(i in 1:nrow(m)){
     res <- paste0(res, paste0(paste(as.character(m[i, 1:ncol(m)]), collapse = "\t"), "\n"))
  }
  return(res)
}

text <- lapply(test, create_text)

writeLines(unlist(text), "listmat.txt")