[Edit: Just to clarify, I am looking for a csv file output that looks exactly like the SparseMatrix, i.e. with blanks in the empty cells and observing the rows and columns]
I’m not sure if I am doing something wrong here, but I specifically want the data to be “clean”, as it were. So I don’t want a dataframe with any headers or anything else but the non-zero values one value per cell.
using SparseArrays, DelimitedFiles
M = sprand(5, 5, 0.5)
Md = Matrix(M) # creates dense Matrix{Float64}
Mb = similar(Md,Any) # similar Matrix{Any}, type Any allows mixing floats with strings
Mb .= Md # assigns content of Md to Mb
Mb[Md .== 0] .= "" # bitmatrix Md.==0 provides indices of all 0's
open("spmatrix_blanks.csv", "w") do io
writedlm(io, Mb, ',')
end
At the moment I’m just using Excel’s conditional formatting on it, otherwise I have to run a macro to get rid of the zeros on the other end. Eventually this step will probably be redundant if I can get the whole thing to run in its own app, but for now this is great.
Tables.table(mat) will wrap a matrix in a tables-compatible object for use with CSV.write.
As for zeros versus missing for the sparse entries, I think there is a package for that, but googling hasn’t gotten me there. But if you can make a sparse matrix where the zero-values are missing, you can pass the option missingstring = "." to CSV.write and you will be good.