I try to write out a matrix to csv while retaining rownames (c.f. Export matrix in r).
However when I do it using write.table() all the columns get shifted to the left (so the first data column header appears above the rownames column).
"PC1","PC2","PC3","PC4"
"Murder",0.0417043206282872,-0.04482165626967,0.0798906594208106,-0.994921731246978
"Assault",0.995221281426497,-0.0587600278572231,-0.0675697350838042,0.03893829763516
"UrbanPop",0.0463357461197111,0.976857479909889,-0.200546287353865,-0.0581691430589317
"Rape",0.0751555005855469,0.200718066450337,0.974080592182492,0.0723250196376096
I tried the following (to manually add an extra column):
merged.pca <- prcomp(USArrests)
write.table(merged.pca$rotation, file = "rotation.csv", sep = ",", col.names = c("rowname",colnames(merged.pca$rotation)))
Unfortunately this fails with:
Error in write.table(merged.pca$rotation, file = "rotation.csv", sep = ",", :
invalid 'col.names' specification
TBH I have no clue what this error means. Is it something about the argument being a list and not a vector?
It is not possible to have duplicate row names, but a simple workaround is creating an extra column (e.g. label) that holds the name that you would assign to your rows. You can then use this column for the names in the graph instead.
The write. table() function is used to export a dataframe or matrix to a file in the R Language. This function converts a dataframe into a text file in the R Language and can be used to write dataframe into a variety of space-separated files for example CSV( comma separated values) files. Syntax: write.table( df, file)
To remove the row names or column names from a matrix, we just need to set them to NULL, in this way all the names will be nullified.
If all else fails, you could make the rownames as column, e. g.
res <- transform(merged.pca$rotation, rowname=rownames(merged.pca$rotation))
write.table(res, "rotation.csv", row.names=FALSE)
Per the help for write.table
, you want to specify col.names=NA
:
write.table(merged.pca$rotation, file="rotation.csv", col.names=NA, sep=",")
Yes, I think it's a bit silly too. Note that write.csv
will do this for you automatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With