R printing to CSV subsetted 'pivot' tables

随声附和 提交于 2019-12-13 07:36:45

问题


I'm trying to write.csv a large number of pivot style tables (as per table b) below:

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

But the CSV output is in the flat format see table_b, where as I would like to show as per the proper table see table a. Any ideas if/how I can achieve this?


回答1:


We can use dcast from the reshape2 package to reshape the data into a three-way table analogous to an Excel pivot 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")

Below is what you get if you leave the data in form of counts instead of calculating row percentages first.



来源:https://stackoverflow.com/questions/34709762/r-printing-to-csv-subsetted-pivot-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!