将矩阵的每一列写入R中的不同文本文件
Posted
技术标签:
【中文标题】将矩阵的每一列写入R中的不同文本文件【英文标题】:Writing each column of a matrix into different text files in R 【发布时间】:2021-03-14 13:45:18 【问题描述】:我有以下矩阵,我想通过仅逐列将行名和多列写入文本文件。有办法吗?
r1 <- c("0","0","0","1","0","0","0","1","0","1","1","0","0")
r2 <- c("1","0","0","1","0","0","0","1","1","0","1","0","0")
r3 <- c("0","1","0","0","1","0","0","0","1","0","0","1","0")
r4 <- c("0","0","1","0","0","1","0","0","1","0","0","0","1")
r5 <- c("0","0","1","0","0","0","1","0","1","0","0","0","1")
n.mat <- rbind(r1,r2,r3,r4,r5)
所以最后我想要 13 个纺织品,每个纺织品包含一个 rowname 列和一个包含 0
和 1
的列。
Textfile 1 Textfile 2 ................
V1 V2
r1 0 r1 0
r2 1 r2 0
r3 0 r3 1
r4 0 r4 0
r5 0 r5 0
【问题讨论】:
【参考方案1】:您可以使用 for
循环并使用例如cat
写出来。
for(i in seq_len(ncol(n.mat))) cat(n.mat[,i], file=paste0("Textfile", i))
并带有标题和列:
for(i in seq_len(ncol(n.mat))) cat(c(paste0("V",i), n.mat[,i]),
file=paste0("Textfile", i), sep="\n")
还有行名(但最好使用write.table
- 只是为了展示它是如何完成的):
for(i in seq_len(ncol(n.mat))) cat(c(paste0(" V",i),
paste(row.names(n.mat), n.mat[,i])), file=paste0("Textfile", i), sep="\n")
【讨论】:
【参考方案2】:我会使用 for 循环,例如:
for (i in 1:ncol(n.mat))
write.table(x = n.mat[, i, drop = FALSE], file = paste0("n.mat.column", i, ".txt"))
【讨论】:
嗨,我收到错误:'警告 if (file == "") file 1并且只使用第一个元素文件中的错误(文件,ifelse(追加,“a”,“w”)):无效的'description'参数' 糟糕,我的论点顺序错误。立即编辑。以上是关于将矩阵的每一列写入R中的不同文本文件的主要内容,如果未能解决你的问题,请参考以下文章
python中对csv文件某一列的每一行文本进行分词后再写到该文件另一列怎么做