I have a matrix with some NA that I’d like to format and then write to a CSV file, replacing each NA with two dashes. However, all of the NA get converted to characters by format, and write.csv then fails to detect and replace them.
After reading through the help file for format, setting na.encode=FALSE seemed like the logical thing to do, but that didn’t fix the problem. I’ve also searched with Google and on this site for other people having this problem, but couldn’t find any. This seems like it should have a simple answer, and has me beating my head against the wall.
A minimal example of my code looks like this:
data = matrix(c(pi, NA, pi*100, NA), 2, 2)
data.f = format(data, digits=4, nsmall=2)
write.csv(data.f, file="data.csv", na="--")
I’m using R 2.15.1. What is the correct way to do this?
Edit: Can anyone explain why this even requires a workaround?
There’s probably a more orthodox way to do this, but perhaps you can use
!is.na()at theformat()stage to prevent theNAvalues from being converted to characters.Here’s a minimal example along with the resulting CSV.