R打印到CSV子集化“枢轴”表 [英] R printing to CSV subsetted 'pivot' tables

查看:158
本文介绍了R打印到CSV子集化“枢轴”表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图write.csv大量的数据透视表样式表(如下表b):

 进口商< -  c(法国,西班牙,德国,法国,西班牙,法国,法国,法国,德国)
出口商 - c(秘鲁,巴西,阿根廷,智利,智利,秘鲁,秘鲁,巴西,巴西)
货物< ,Wine,Wine,Cars,Bananas,Bananas,Cars,Bananas,Wine)
df< -data.frame(import,exporter,货物)
table_a< - table(df $ importer,df $ exporter)
write.csv(table_a,table_a.csv)
table_b < df $ exporter,df $ goods)
write.csv(table_b,table_b.csv)

但CSV输出采用平面格式



以下是您以计数形式保留数据而不是首先计算行百分比。




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?

解决方案

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.

这篇关于R打印到CSV子集化“枢轴”表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆