【问题标题】:Summarise unique combinations in data frame总结数据框中的独特组合
【发布时间】:2013-03-25 11:57:38
【问题描述】:

在下面的示例数据集中,我需要找到每年汇总的每种产品的唯一客户数。输出必须是带有标题的 data.frame:year - product - number of customers

感谢您的帮助。

year <- c("2009", "2010")
product <- c("a", "b", "c")
df <- data.frame(customer = sample(letters, 50, replace = T),
                 product = sample(product, 50, replace = T),
                 year = sample(year, 50, replace = T))

【问题讨论】:

  • 我不会反对这个。但是,一个没有研究成果的问题很可能会被否决。如果可能,请编辑您的问题,向我们展示您到目前为止所管理的内容。

标签: r


【解决方案1】:

使用aggregate()(包含在 R 统计包中):

agdf<-aggregate(customer~product+year,df,function(x)length(unique(x)))
agdf
#  product year customer
#1       a 2009        7
#2       b 2009        8
#3       c 2009       10
#4       a 2010        7
#5       b 2010        7
#6       c 2010        6

【讨论】:

    【解决方案2】:

    使用plyrsummarise

    require(plyr)
    ddply(df, .(product, year), summarise, customers=length(unique(customer)))
    

    【讨论】:

      猜你喜欢
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      • 1970-01-01
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多