I want to append by columns a matrix to an existing file without binding the matrices previously in R. This is an example:
A <- data.table(matrix(1:9, 3))
names(A) <- as.character(1:3)
B <- data.table(matrix(10:18, 3))
names(B) <- as.character(4:6)
fwrite(A, file = "test.txt", sep = " ", row.names = FALSE, col.names = FALSE)
fwrite(B, file = "test.txt", sep = " ", row.names = FALSE, col.names = FALSE, append = T)
I tried to change column names without sucess. The result is the following:
> fread("test.txt")
V1 V2 V3
1: 1 4 7
2: 2 5 8
3: 3 6 9
4: 10 13 16
5: 11 14 17
6: 12 15 18
And this is what I am looking for:
1 4 7 10 13 16
2 5 8 11 14 17
3 6 9 12 15 18
I know that in my example I could simply run AB <- cbind(A, B)
and than just fwrite(AB)
, but in practice I cannot do that given that A
and B
are extremely large matrices and I don't have enough memory to allocate a combined matrix.
Notice that this may not be doable with fwrite()
so I am open to other methods.
Edit
I found a temporary solution by transposing the matrices :
A <- data.table(t(matrix(1:9, 3)))
B <- data.table(t(matrix(10:18, 3)))
fwrite(A, file = "test.txt", sep = " ", row.names = FALSE, col.names = FALSE)
fwrite(B, file = "test.txt", sep = " ", row.names = FALSE, col.names = FALSE, append = T)
> t(fread("test.txt"))
[,1] [,2] [,3] [,4] [,5] [,6]
V1 1 4 7 10 13 16
V2 2 5 8 11 14 17
V3 3 6 9 12 15 18
This solution is not ideal, so I am still looking forward if someone comes up with something better.