我现在花了一些时间学习reshape2
,plyr
但我仍然不明白。这次我遇到了(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'))
现在我的问题:
我已经能够在行中添加小计。但是是否也可以在列中添加边距。例如,一个出版商的库存总额?抱歉,我的意思是说所有出版商的总销量示例。“比率”列存在问题。我怎样才能得到这个变量的“平均值”而不是“总和”?
请注意:第一个问题(关于边距小计)可以解决。
PS:我看过一些使用reshape
. 你会推荐使用它来代替reshape2
(这似乎不包括两个函数的功能)。