0

我现在花了一些时间学习reshape2plyr但我仍然不明白。这次我遇到了(a)小计和(b)传递不同聚合函数的问题。这里是一个使用mrdwab 博客上教程中的数据的示例

# libraries 
library(plyr)
library(reshape2)
# get data and add few more variables 
book.sales = read.csv("http://news.mrdwab.com/data-booksales")
book.sales$Stock = book.sales$Quantity + 10
book.sales$SubjCat[(book.sales$Subject == 'Economics') | 
  (book.sales$Subject == 'Management')] <- '1_EconSciences'
book.sales$SubjCat[book.sales$Subject %in% 
  c('Anthropology', 'Politics', 'Sociology')] <- '2_SocSciences'
book.sales$SubjCat[book.sales$Subject %in% c('Communication', 'Fiction',
  'History', 'Research', 'Statistics')] <- '3_other'

# to get to my starting dataframe (close to the project I am working on) 
book.sales1 <- ddply(book.sales, c('Region', 'Representative', 'SubjCat', 
                                   'Subject', 'Publisher'), summarize,
                 Stock = sum(Stock), Sold = sum(Quantity),
                 Ratio = round((100 * sum(Quantity)/sum(Stock)), digits = 1))


#melt it 
m.book.sales = melt(data = book.sales1, id.vars = c('Region', 'Representative',
                                        'SubjCat', 'Subject', 'Publisher'),
                    measured.vars = c('Stock', 'Sold', 'Ratio'))

# cast it --- # Please ignore this cast this was a mistake 
# Tab1 <- dcast(data = m.book.sales, 
#         formula = Region + Representative ~ Publisher + variable,
#         fun.aggregate = sum, margins = c('Region', 'Representative'))

Tab1 <- dcast(data = m.book.sales, formula = Region + Representative ~ 
  SubjCat + Subject + variable, fun.aggregate = sum,
              margins = c('Region', 'Representative', 'SubjCat', 'Subject'))

现在我的问题:

  1. 我已经能够在行中添加小计。但是是否也可以在列中添加边距。例如,一个出版商的库存总额?抱歉,我的意思是说所有出版商的总销量示例。

  2. “比率”列存在问题。我怎样才能得到这个变量的“平均值”而不是“总和”?

请注意:第一个问题(关于边距小计)可以解决。

PS:我看过一些使用reshape. 你会推荐使用它来代替reshape2(这似乎不包括两个函数的功能)。

4

1 回答 1

2

不确定您对问题 1 到底想要什么,但如果您想要总库存量,Publisher您不只是这样做吗?

 totalofstock <- ddply(book.sales, ('Publisher'), function(x)   
                      data.frame=c(subtotals  =  sum(x$Stock)))

如果您想将其添加到Tab1您身上,只需执行以下操作:

Tab1$bloomsburytotalofstock<-totalofstock[1,][[2]]
head(Tab1)

至于问题 2 得到 amean而不是 asum肯定你会将函数从 更改summean

例如

ratiomeans <- ddply(book.sales1, ('Publisher'), function(x)   
                      data.frame=c(ratioMEAN  =  mean(x$Ratio)))

另外我建议坚持使用reshape2. reshape2基本上是新版本的reshape。据我所知reshape,不再工作但仍然存在,因此使用旧代码的人reshape不必重写所有内容。

编辑

justratio<-(m.book.sales[m.book.sales$variable=="Ratio",])
Tab2 <- dcast(data = justratio, 
        formula = Region + Representative ~ SubjCat + Subject + variable,
        fun.aggregate = mean,
        margins = c('Region', 'Representative', 'SubjCat', 'Subject'))
final<-merge(Tab1,Tab2,by=c("Region","Representative"))
于 2012-09-16T09:17:26.513 回答