在R中分组和计数

时间:2015-02-25 00:54:38

标签: r

我有一个shell程序来执行以下操作,但我想尝试一下R,我很难过。

我的数据集如下所示:

 <date>      <car>        <sale>   
 2014-05-08 mercedes-450  40000
 2014-05-08 mercedes-350  30000
 2014-05-08 mercedes-350  30000
 2014-05-08 toyota corolla 20000
 2014-05-08 toyota camry   30000
 2014-05-09 mercedes-450  40000
 2014-05-09 mercedes-450  40000

我想将此转换为2个数据框,一个用于梅赛德斯,一个用于丰田。

所以梅赛德斯:

 2014-05-08 mercedes  100000
 2014-05-09 mercedes  80000

和丰田:

 2014-05-08 toyota  50000

我需要这样做,所以我可以在不同的图表上绘制丰田和梅赛德斯的销售情况,其中x轴为日期,y为销售。

如何创建两个数据框?我尝试了ddply,但我得到的只是一个看起来像这样的数据跟踪

 ddply(sales,c("date","car_type"),numcolwise(sum))

 2014-05-08 mercedes-450  40000
 2014-05-08 mercedes-350  60000
 2014-05-08 toyota corolla  20000

3 个答案:

答案 0 :(得分:1)

# sample data
set.seed(1)
df = data.frame(date = rep(as.Date(c("10jan1970", "11jan1970", "31mar1960", "30jul1960"), "%d%b%Y"), 2),
                type = sample(1:2, 8, replace=T),
                sales = rnorm(8))

# "aggreate()" to calculate your daily sales
agg = aggregate(sales ~ date + type, data=df, FUN=sum)

# "split()" the result by type if you want different data frames for each type
tabs = split(agg, f=agg$type)
tabs

# $`1`
#         date type      sales
# 1 1970-01-10    1  0.9052891
# 2 1970-01-11    1 -0.8204684
#
# $`2`
#         date type      sales
# 3 1960-03-31    2  1.9992102
# 4 1960-07-30    2  1.1281679
# 5 1970-01-11    2 -0.3053884

答案 1 :(得分:1)

加载数据框:

df <- data.frame(
  date = c("2014-05-08","2014-05-08","2014-05-08","2014-05-08","2014-05-08","2014-05-09","2014-05-09"),
  car = c("mercedes-450","mercedes-350","mercedes-350","toyota corolla","toyota camry","mercedes-450","mercedes-450"),
  sale = c(40000,30000,30000,20000,30000,40000,40000),stringsAsFactors=FALSE)

通过将汽车变量拆分为&#34;来创建汽车制造的新变量 - &#34;和&#34; &#34;:

splitstring <- strsplit(df$car," |-")
df$make <- unlist(lapply(splitstring,"[[",1))

加载我们用来计算分组总和的dplyr包:

library(dplyr)

按日计算销售额总和:

results <- df %>%
  group_by(date,make) %>%
  summarise(total_sales = sum(sale))

现在,如果您想为每个品牌创建不同的图表,可以在类似ggplot2的包中使用make作为facet变量,并将数据保存在单个表中。 但是如果你想为每个制作不同的表

tables <- split(results,results$make)

答案 2 :(得分:0)

ddply解决方案:

library(plyr)

A<-df[grep("mercedes", df$car), ]
B<-df[grep("toyota", df$car), ]

ddply(A, .(date), summarize, val = sum(sale)) 
ddply(B, .(date), summarize, val = sum(sale))