我尝试在保留rownames的同时向csv写出一个矩阵(c.f。Export matrix in r)。
但是当我使用write.table()执行此操作时,所有列都会向左移动(因此第一个数据列标题显示在rownames列上方)。
"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
我尝试了以下操作(手动添加额外的列):
merged.pca <- prcomp(USArrests)
write.table(merged.pca$rotation, file = "rotation.csv", sep = ",", col.names = c("rowname",colnames(merged.pca$rotation)))
不幸的是,这失败了:
Error in write.table(merged.pca$rotation, file = "rotation.csv", sep = ",", :
invalid 'col.names' specification
TBH我不知道这个错误意味着什么。它是关于参数是列表而不是向量的东西吗?
答案 0 :(得分:11)
根据write.table
的帮助,您要指定col.names=NA
:
write.table(merged.pca$rotation, file="rotation.csv", col.names=NA, sep=",")
是的,我认为这也有点傻。请注意write.csv
会自动为您执行此操作。
答案 1 :(得分:3)
如果所有其他方法都失败了,您可以将rownames设为列,e。克。
res <- transform(merged.pca$rotation, rowname=rownames(merged.pca$rotation))
write.table(res, "rotation.csv", row.names=FALSE)
答案 2 :(得分:1)
不确定我是否完全理解,但我的镜头是:
只需使用
即可保存矩阵write.csv( merged.pca$rotation, file = "rotation.csv", row.names = TRUE )
使用
加载它(作为data.frame!)x <- read.csv( "rotation.csv" )
并使用
将其恢复为之前的格式row.names( x ) <- x[,1]
x <- as.matrix( x[-1] )
这就是你想要的吗?
答案 3 :(得分:0)
此解决方案保存列结构(即Excel)和名称:
write.csv(x, file = "foo.csv", fileEncoding = "macroman")
write.csv(x, file = "foo.csv", fileEncoding = "UTF-16LE")