R 打印到 CSV 子集 'pivot' 表

R printing to CSV subsetted 'pivot' tables

我正在尝试 write.csv 下面的大量枢轴样式 tables(根据 table b):

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, where as I would like to show as per the proper table see table a。任何想法 if/how 我可以实现这个吗?

我们可以使用 reshape2 包中的 dcast 将数据重塑为 three-way table 类似于 Excel 枢轴 table:

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")

如果您将数据保留为计数形式而不是先计算行百分比,则会得到以下结果。