2017-01-09 40 views
-1

您好我想用的日期和独特的价值聚合,使得:集料的日期和唯一的组

Date  Client_id  Purchase 
01-01-2016 00001   Wine 
01-01-2016 00001   Beer 
01-01-2016 00002   Wine 
02-01-2016 00003   Beer 
02-01-2016 00004   Wine 
03-01-2016 00005   Beer 

所以我有这样的事情:

Date  Number of Clients 
01-01-2016  2 
02-01-2016  2 
03-01-2016  1 

我与尝试dplyr和基地R聚合功能,但我没有成功:

daily_customers <- df %>% sum(date) %>% unique(Client_id) 
daily_customers <- aggregate(Date~ unique(client_id)) 

任何建议?

回答

1
library(dplyr) 
df %>% group_by(Date) %>% summarise("Number of Clients" = length(unique(Client_id))) 

library(data.table) 
df[ , .("Number of Clients" = length(unique(Client_id))), by = .(Date)] 

#  Date Number of Clients 
#1 01-01-2016     2 
#2 02-01-2016     2 
#3 03-01-2016     1 
+0

优雅,谢谢! 。 – adrian1121

0
> library(plyr) 
> count(x,'Date') 

     Date freq 
1 01-01-2016 3 
2 02-01-2016 2 
3 03-01-2016 1 
+0

请检查OP所需的o/p。 –

1

在dplyr,你也可以使用n_distinct()而是采用length(unique())

df %>% 
group_by(Date) %>% 
summarise(nOfClients = n_distinct(Client_id)) 

#  Date nOfClients 
#  <fctr>  <int> 
#1 01-01-2016   2 
#2 02-01-2016   2 
#3 03-01-2016   1 
相关问题