2016-01-10 7 views
0

我试图write.csv大量枢轴式表(根据表b)所示:R丝网印刷到CSV子集“枢轴”表

importer <- c("France", "Spain", "Germany", "France", "Spain", "France", "France", "France", "Germany") 
exporter <- c("Peru", "Brazil", "Argentina", "Chile", "Chile", "Peru", "Peru", "Brazil", "Brazil") 
goods <- c("Apples", "Wine", "Wine", "Cars", "Bananas", "Bananas", "Cars", "Bananas", "Wine") 
df <-data.frame(importer, exporter, goods) 
table_a <- table(df$importer, df$exporter) 
write.csv(table_a, "table_a.csv") 
table_b <- table(df$importer, df$exporter, df$goods) 
write.csv(table_b, "table_b.csv") 

但CSV输出是在平坦格式see table_b,我想按照适当的表see table a显示。任何想法如果/我该如何实现这一目标?

+0

你可以使用'?capture.output' – akrun

回答

1

我们可以使用dcastreshape2包到数据重塑成三路表类似于Excel数据透视表:

library(reshape2) 

pivot3 = dcast(df, goods + importer ~ exporter, fun.aggregate = length) 

# Convert values to percent of row 
pivot3[, sapply(pivot3, is.numeric)] = 
     pivot3[, sapply(pivot3, is.numeric)]/rowSums(pivot3[, sapply(pivot3, is.numeric)]) 

write.csv(pivot3, "table_c.csv") 

enter image description here

下面是如果你离开了你会得到什么以计数形式的数据,而不是首先计算行百分比。

enter image description here

+0

这是非常好的非常感谢。有没有一种方法可以获得这些数据占行总数的百分比而不是数?我以前一直在使用'prop.table(table_b,1)'来达到这个目的? – Rob

+0

查看更新。 'sapply(pivot3,is.numeric)'选择具有数字值的列。然后我们使用数字列来计算每行的行总数的百分比。 – eipi10

+0

这是辉煌的,工作的一种享受。非常感谢! – Rob