我尝试写出一个矩阵到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' specificationTBH我不知道这个错误是什么意思。它是关于参数是一个列表而不是一个向量吗?
发布于 2013-06-23 20:14:10
根据write.table的帮助,您需要指定col.names=NA
write.table(merged.pca$rotation, file="rotation.csv", col.names=NA, sep=",")是的,我也觉得这有点傻。请注意,write.csv将自动为您完成此操作。
发布于 2013-06-23 02:18:34
如果所有其他方法都失败了,你可以将行名设为列,例如。
res <- transform(merged.pca$rotation, rowname=rownames(merged.pca$rotation))
write.table(res, "rotation.csv", row.names=FALSE)发布于 2013-06-23 20:08:36
我不确定我是否完全理解,但我的想法是:
只需使用以下命令即可保存矩阵
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] )这是你想要的吗?
https://stackoverflow.com/questions/17252894
复制相似问题