【问题标题】:R printing to CSV subsetted 'pivot' tablesR打印到CSV子集的“数据透视”表
【发布时间】:2016-04-15 01:36:34
【问题描述】:

我正在尝试在下面编写.csv 大量数据透视表(根据表 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,我想按照正确的表格 see table a 显示。如果/如何实现这一目标有什么想法吗?

【问题讨论】:

  • 你可以使用?capture.output

标签: r csv pivot-table export-to-csv


【解决方案1】:

我们可以使用 reshape2 包中的 dcast 将数据重塑为类似于 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")

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

【讨论】:

  • 非常感谢。有没有办法让我以行总数的百分比而不是计数来获取这些数据?我以前一直在使用prop.table(table_b, 1) 来实现这一目标?
  • 查看更新。 sapply(pivot3, is.numeric) 选择具有数值的列。然后我们使用数字列来计算每行占总行数的百分比。
猜你喜欢
  • 2020-03-22
  • 2019-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多