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

问题描述 投票:0回答:1

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

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)

文本文件如下所示:

似乎矩阵被打印为矢量。如何更改代码以便将它们打印为矩阵?

谢谢!

r
1个回答
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")
© www.soinside.com 2019 - 2024. All rights reserved.