I’m having trouble with the code that I write below. I need to compute the distance matrix for each row of my input matrix (aa) and save the result in a file with the rowname as filename.
The aa matrix is a 100×100, but a test matrix look like this:
ID A B C D
AA 0.5 0.4 0.9 0.5
BB 0.2 0.1 0.8 0.96
CC 0.3 0.5 0.8 0.4
DD 0.1 0.4 0.5 0.78
Pratically I would like to obtain a single file for each row containing the distance matrix and with “AA.txt” and “BB.txt” and “CC.txt” and “DD.txt” as filenames.
a<- read.table ("test_matrix.txt", header = TRUE)
aa<- structure (a, class = "data.frame")
d_ply(aa, 1, function(row){
cu<- dist(as.numeric(row))
cucu<- as.matrix(cu)
write.table(cucu, quote = TRUE, file = paste(row$ID, "txt", sep = "."), sep = "\t")
}, .progress='text', .print = TRUE)
Using the code above I obtain the correct filenames, but the content is not right because I have a 5×5 matrix instead of a 4×4 one. Can someone tell me which is the problem? I guess something in reading the header…
Thank you!
When I run your code, the output looks like:
You’ll want to adjust your function to include both my and Joran’s advice:
Running
d_ply(aa, 1, myfun, .print=TRUE)gives files that look like: