I’m having trouble with a R code that I wrote. Particularly it looks like this:
n<- nrow(aa)
for (i in 1:n)
{
A<- aa[i,]
d_ply(A, 1, function(row){
cu<- dist(A)
write.table(cu, file = paste(row$header, "txt", sep = "."), sep = "\t")
}, .progress='text', .print = TRUE)
}
I would like to obtain a single file from each row of aa matrix (the file name should be the header of the row), containing the distance matrix of that row, but seems very hard. If I try the code I get this error:
cannot coerce class '"dist"' into a data.frame
How can I solve this?
First, assuming
aais a data frame, thenAis just a single row. You don’t need to use the for loop if you’re already usingd_ply, which is designed to apply something to every row of a data frame.The second issue is that
distreturns adistobject, which has to be turned into a matrix before it can be written. The following code will do that:Third, you need to convert the
rowfrom a one-row data frame to a vector before usingdist.This leads to the following code: