2016-02-21 90 views
-1

我在我的数据集中有多个因子(“a”,“b”,“c”),每个因子都有对应的价格和成本值。R dplyr - 不同因素的总和值

dat <- data.frame(
ProductCode = c("a", "a", "b", "b", "c", "c"), 
Price = c(24, 37, 78, 45, 20, 34), 
Cost = c(10,15,45,25,10,17) 
) 

我正在寻找每个ProductCode的价格和成本的总和。

by.code <- group_by(dat, code) 
by.code <- summarise(by.code, 
         SumPrice = sum(Price), 
         SumCost = sum(Cost)) 

此代码不起作用,因为它汇总了列中的所有值,而没有将它们分类为类别。

SumPrice SumCost 
1  238  122 

在此先感谢您的帮助。

+0

你可能有plyr函数名称冲突。用'dplyr :: summarize(...)试试你的代码' –

回答

1

这不是dplyr - 这个答案是你,如果你不介意的sqldfdata.table包:

sqldf("select ProductCode, sum(Price) as PriceSum, sum(Cost) as CostSum from dat group by ProductCode") 

ProductCode PriceSum CostSum 
     a  61  25 
     b  123  70 
     c  54  27 

使用data.table包:

library(data.table) 
MM<-data.table(dat) 
MM[, list(sum(Price),sum(Cost)), by = ProductCode] 

ProductCode V1 V2 
1:   a 61 25 
2:   b 123 70 
3:   c 54 27 
1

你的代码工作正常。只有一个错字。您应该将您的列的ProductionCode命名为代码,并且您的代码正常工作。我只是这样做了,R正在给出适当的输出。下面是代码:

library(dplyr) 
dat <- data.frame(
code = c("a", "a", "b", "b", "c", "c"), 
Price = c(24, 37, 78, 45, 20, 34), 
Cost = c(10,15,45,25,10,17) 
) 
dat 
by.code <- group_by(dat, code) 
by.code <- summarise(by.code, 
         SumPrice = sum(Price), 
         SumCost = sum(Cost)) 
by.code 
+0

谢谢你。我试过这段代码 - 它仍然不起作用。你确定它给了你适当的输出吗? –

+0

此解决方案适用于我。 –

0

我们可以使用aggregatebase R

aggregate(.~ProductCode, dat, sum) 
# ProductCode Price Cost 
#1   a 61 25 
#2   b 123 70 
#3   c 54 27