我正在R中使用ftable
来创建列联表。
我想将一个ftable对象打印到一个csv,但是当我在ftable对象上使用write.csv()
时,csv不再列出R的ftable中包含的因子名称。这是输出的类型我得到
这是R中的示例ftable
structure(c(1L, 0L, 0L, 0L, 1L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 1L, 2L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L,
1L, 1L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L,
0L, 1L, 0L, 2L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L,
0L, 1L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 1L, 0L, 0L,
0L, 0L, 1L, 0L, 0L, 0L, 0L), .Dim = c(12L, 7L), class = "ftable", row.vars = list(
ï..petal_size = c("large ", "small", "small "), stem_length = c("long",
"long ", "short", "short ")), col.vars = list(flow_color = c("blue",
"green", "indigo ", "orange", "red ", "violet", "yellow")))
是否有解决方案,以便我可以保留因子名称?
答案 0 :(得分:2)
一种选择是使用函数write.ftable
,但是由于所有内容(在CSV文件中)都将写在单个列中,因此您将需要做很多手工工作
write.ftable(ftable(df), file = "table.csv", quote = FALSE)
# And the otuput NOTE: WHEN OPENING CSV EVERYTHING WILL BE IN SINGLE COLUMN
flow_color blue green indigo orange red violet yellow
i..petal_size stem_length
large long 1 0 1 1 2 1 1
long 0 0 0 0 0 0 0
short 0 0 0 0 0 1 1
short 0 1 0 1 0 0 0
small long 1 2 0 0 1 0 0
long 0 0 1 0 0 0 0
short 0 0 1 0 0 1 0
short 1 0 0 0 0 0 1
small long 0 0 0 0 0 0 0
long 0 0 0 0 0 0 0
short 0 0 0 1 0 0 0
short 0 0 0 0 0 0
0
或者使用stats
的另一种选择是先格式化ftable
然后使用write.table
df <- ftable(df)
cont <- stats:::format.ftable(df, quote = FALSE)
write.table(cont, sep = ";", file = "table.csv")