I have following matrix, and I would like to write rownames and multiple columns into a text file by only taking column by column. Is there a way of doing so?
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)
So in the end I would like to have 13 textiles each containing a rowname column and one column containing the 0
and 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
You can use a for
loop and use e.g. cat
to write it out.
for(i in seq_len(ncol(n.mat))) {cat(n.mat[,i], file=paste0("Textfile", i))}
and with a header and in column:
for(i in seq_len(ncol(n.mat))) {cat(c(paste0("V",i), n.mat[,i]),
file=paste0("Textfile", i), sep="\n")}
And with rownames (but better use write.table
- only to show how it could be done):
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")}