[英]How to make write.table retain dimnames?
I need to save a number of tables in a single CSV file and am having difficulty seeing how to retain dimension names. 我需要在一个CSV文件中保存大量表格,并且很难看到如何保留维度名称。 I searched SO and the closest I found was: How to get dimnames in xtable.table output?
我搜索了SO,我找到的最接近的是: 如何在xtable.table输出中获取dimnames? The problem he has with xtable is the problem I've got with write.table – dimnames exist in the table (and prop.table and ftable as well if I use that) but get dropped by write.table.
他对xtable的问题是我用write.table得到的问题 - 表中存在dimnames(如果我使用的话,还有prop.table和ftable)但是被write.table删除了。 I'm using write.table not write.csv for append=T.
我正在使用write.table而不是write.csv for append = T.
The dataset is from a survey and the aim is to create the complete set of crosstabs, with labelled axes. 数据集来自调查,目的是创建带有标记轴的完整交叉表集。 In this case, actual row/column labels are not important, only dimension labels.
在这种情况下,实际的行/列标签并不重要,只有维度标签。 I'm new to R, so hope I haven't missed something obvious.
我是R的新手,所以希望我没有错过任何明显的东西。
d<-read.csv('dataset.csv') # dataset with column headings, no row labels
cat('BEGIN\n',file='xtabs.csv')
for (i in 1:ncol(d)) {
for (j in 1:ncol(d)) {
cat(paste('\ni=',i,' j=',j,'\n'),file='xtabs.csv',append=T)
t<-table(d[,i],d[,j],dnn=c(names(d[i]),names(d[j])))
pt<-prop.table(t,1)
write.table(pt,'xtabs.csv',sep=',',dec='.',row.names=F,col.names=F,append=T)
print(pt) # shows dimnames in the console as expected
}
}
Try this: 试试这个:
tbl <- with(warpbreaks, table(wool, tension))
pt <- prop.table(tbl)
write.ftable(ftable(pt),file = "~/Desktop/table.csv", sep = ",",
quote = FALSE)
I'm possibly abusing ftable
s here, which are intended for multi-dimensional tabular data (ie more than two variables). 我可能在这里滥用
ftable
,它们用于多维表格数据(即两个以上的变量)。 But it's the only thing I've found that will write the table to a text file with (seemingly) the formatting you want. 但这是我发现的唯一能将表格写入文本文件(看似)你想要的格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.