【问题标题】:R-How to count unique number of rows based on another column [duplicate]R-如何根据另一列计算唯一行数[重复]
【发布时间】:2016-03-09 21:10:37
【问题描述】:

我正在处理大量客户数据,并试图找出客户每月光顾的商店的平均数量。在我的数据中,我有每个客户的唯一标识号和他们访问的商店代码。我的数据框示例如下所示:

sitecode<-c(1000,1000,1001,1000)
productcode<-c('X','X','Y','X')
customercode<-c('A','B','A','C')
Date<-c('01/01/2016','02/01/2016','03/01/2016','04/01/2016')
data1<-data.frame(customercode,Date,productcode,sitecode)

基于此,我希望为客户 A-B-C 提供一个简单的表格,其中包含他们访问过的商店的唯一数量,即 A 为 2,B 和 C 为 1。你能帮忙吗?

【问题讨论】:

  • table(data1$customercode) ?
  • tapply(data1$sitecode, data1$customercode, function(x) length(unique(x)))?
  • @mtoto 那行不通。例如,客户 B 可以访问同一个站点两次,因此 table(data1$customercode) 将为 B 提供 2。但在这种特殊情况下,由于客户 B 访问的站点的唯一数量是 1,我希望看到 1。跨度>
  • 我想这有你的答案:stackoverflow.com/q/32457598/1191259如果你确认,我们可以关闭问题。
  • @Frank 非常感谢,tapply(data1$sitecode, data1$customercode, function(x) length(unique(x)))。它对我有用。

标签: r unique rowcount


【解决方案1】:
data1
# customercode       Date productcode sitecode
# 1            A 01/01/2016           X     1000
# 2            B 02/01/2016           X     1000
# 3            A 03/01/2016           Y     1001
# 4            C 04/01/2016           X     1000


result=table(data1$customercode,data1$sitecode)
result

  1000 1001
A    1    1
B    1    0
C    1    0

希望这在一定程度上有所帮助。

【讨论】:

    猜你喜欢
    • 2019-02-11
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 2023-01-03
    • 2021-12-26
    相关资源
    最近更新 更多